Adding multiple points in map using polyline and arraylist - android

How to draw a polyline in google map for multiple latitude and longitude coordinates. I need to draw polyline for atleast 20 sets of latitude and longitude dynamically.

Adding multiple points in map using polyline and arraylist
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
// Adding points to ArrayList
coordList.add(new LatLng(0, 0);
coordList.add(new LatLng(1, 1);
coordList.add(new LatLng(2, 2);
// etc...
// Find map fragment. This line work only with support library
GoogleMap gMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
PolylineOptions polylineOptions = new PolylineOptions();
// Create polyline options with existing LatLng ArrayList
polylineOptions.addAll(coordList);
polylineOptions
.width(5)
.color(Color.RED);
// Adding multiple points in map using polyline and arraylist
gMap.addPolyline(polylineOptions);

Example from Android documentation:
GoogleMap map;
// ... get a map.
// Add a thin red line from London to New York.
Polyline line = map.addPolyline(new PolylineOptions()
.add(new LatLng(51.5, -0.1), new LatLng(40.7, -74.0))
.width(5)
.color(Color.RED));
Just call .add as many times as you need.

Just create a function to retrieve JSON polylines as this:
private ArrayList<LatLng> getPolylines(String jsonStr) {
// file exists, it is the first boot
if (jsonStr != null) {
// linea init
LatLng polyline;
// array list of lines init
ArrayList<LatLng> polylines = new ArrayList<LatLng>();
// get json array
JSONArray jsonArray = JSON.getJSONArray(jsonStr, "polytag");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonPolyline;
try {
jsonPolyline = jsonArray.getJSONObject(i);
polyline = new LatLng(Double.valueOf(jsonPolyline.getString("lat")),
Double.valueOf(jsonPolyline.getString("lon")));
polylines.add(polyline);
} catch (JSONException e) {
Log.d(TAG, "JSONException reading polylines: " + e.getMessage());
} catch (Exception e) {
Log.d(TAG, "Exception reading polylines: " + e.getMessage());
}
}
return polylines;
}
return null;
}
Then get this ArrayList and populate it in this way:
ArrayList<LatLng> polylines = getPolylines(linesJsonStr);
map.addPolyline(new PolylineOptions().addAll(polylines).width(2.0f).color(Color.RED));
Hope it helps!

You can iterate over the array of points and for each of the coordinates add a new LatLng to polyline options then after the loop add the polyline option to the polyline.
val from = LatLng(it.data[0].lat, it.data[0].lng)
val to = LatLng(it.data.last().lat, it.data.last().lng)
map.addMarker(MarkerOptions().position(from).title("pickup location"))
map.addMarker(MarkerOptions().position(to).title("destination location"))
map.animateCamera(CameraUpdateFactory.newLatLngZoom(from, 13f))
var polylineOptions = PolylineOptions()
for (i in it.data){
polylineOptions.add(LatLng(i.lat, i.lng))
}
polylineOptions.width(5f).color(Color.RED)
map.addPolyline(
polylineOptions
)

Related

How to show a polyline on Google map using JSON array of latitude and JSON array of longitude?

I'm making an app that needs to show a line on Google map. Coordinates for the polyline are in separate JSON arrays – one array for latitude and one for longitude. My question is how do I get the data from JSON url and to show the polyline on map?
Here is my JSON structure:
{“1”: { “id”:”1”,"lat_list":[43.193850940837,43.193553712737,43.193225195784,43.193131333473,43.193146977202],"lng_list":[23.284599781036,23.28423500061,23.28382730484,23.283634185791,23.283518850803]}}
Thank you in advance!
I hope this helps, and you should notice to replace ” and “ with ". You can also take a look at google map polyline and polygon tutorial for more details about google map polygons.
try {
JSONObject obj = new JSONObject("{\"1\": { \"id\":\"1\",\"lat_list\":[43.193850940837,43.193553712737,43.193225195784,43.193131333473,43.193146977202],\"lng_list\":[23.284599781036,23.28423500061,23.28382730484,23.283634185791,23.283518850803]}}");
JSONObject obj2 = obj.getJSONObject("1");
JSONArray lat_list = obj2.getJSONArray("lat_list");
JSONArray lng_list = obj2.getJSONArray("lng_list");
PolylineOptions polyLineOptions = new PolylineOptions()
.clickable(true);
for (int i = 0; i < lat_list.length() && i < lng_list.length(); i++) {
double lat = lat_list.getDouble(i);
double lng = lng_list.getDouble(i);
polyLineOptions.add(lat, lng);
}
googleMap.addPolyline(polyLineOptions);
} catch (JSONException e) {
e.printStackTrace();
}

Plotting coordinates on Route in Gmap (Google Maps Android API)

I'm currently working on one Android application using Google map.
My requirement is to draw a route between source-destination and plot markers at every 500 meters on that route.
I have drawn a route, but not getting how to plot markers at every 500 meters. Is there any Google API available to get coordinates on route, or I have to implement any other logic?
Objectives
The objective is getting a list of LatLng coordinates along the route returned by the Directions API web service at every N meters. Later we can create markers for this list of coordinates.
Solution
The solution has two steps. The first one is getting a list of LatLng that form a route returned by Directions API. You can use a Java Client for Google Maps Services to execute Directions API request and extract a list of LatLng. Have a look at private List<LatLng> getDirectionsPathFromWebService(String origin, String destination) method in my example. This method calls Directions API and loop through legs and steps of the route object to get a complete list of LatLng that form a route.
The second step is implemented in the method private List<LatLng> getMarkersEveryNMeters(List<LatLng> path, double distance). It loops through all LatLng from the first step and creates a list of LatLng at every N meters where N is a distance in meters passed as a second parameter of the method. This method uses internally SphericalUtil class from the Google Maps Android API Utility Library. Have a look at comment to figure out what is happening in this method.
Finally, I create markers from the list that was obtained in second step.
Code snippet
public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
private GoogleMap mMap;
private String TAG = "so47784512";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
// Obtain the SupportMapFragment and get notified when the map is ready to be used.
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
.findFragmentById(R.id.map);
mapFragment.getMapAsync(this);
}
#Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
String origin = "Avinguda Diagonal, 101, 08005 Barcelona, Spain";
String destination = "Carrer de París, 67, 08029 Barcelona, Spain";
LatLng center = new LatLng(41.391942,2.179413);
//Define list to get all latlng for the route
List<LatLng> path = this.getDirectionsPathFromWebService(origin, destination);
//Draw the polyline
if (path.size() > 0) {
PolylineOptions opts = new PolylineOptions().addAll(path).color(Color.BLUE).width(5);
mMap.addPolyline(opts);
}
List<LatLng> markers = this.getMarkersEveryNMeters(path, 500.0);
if (markers.size() > 0) {
for (LatLng m : markers) {
MarkerOptions mopts = new MarkerOptions().position(m);
mMap.addMarker(mopts);
}
}
mMap.getUiSettings().setZoomControlsEnabled(true);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(center, 13));
}
private List<LatLng> getDirectionsPathFromWebService(String origin, String destination) {
List<LatLng> path = new ArrayList();
//Execute Directions API request
GeoApiContext context = new GeoApiContext.Builder()
.apiKey("AIzaSyBrPt88vvoPDDn_imh-RzCXl5Ha2F2LYig")
.build();
DirectionsApiRequest req = DirectionsApi.getDirections(context, origin, destination);
try {
DirectionsResult res = req.await();
//Loop through legs and steps to get encoded polylines of each step
if (res.routes != null && res.routes.length > 0) {
DirectionsRoute route = res.routes[0];
if (route.legs !=null) {
for(int i=0; i<route.legs.length; i++) {
DirectionsLeg leg = route.legs[i];
if (leg.steps != null) {
for (int j=0; j<leg.steps.length;j++){
DirectionsStep step = leg.steps[j];
if (step.steps != null && step.steps.length >0) {
for (int k=0; k<step.steps.length;k++){
DirectionsStep step1 = step.steps[k];
EncodedPolyline points1 = step1.polyline;
if (points1 != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords1 = points1.decodePath();
for (com.google.maps.model.LatLng coord1 : coords1) {
path.add(new LatLng(coord1.lat, coord1.lng));
}
}
}
} else {
EncodedPolyline points = step.polyline;
if (points != null) {
//Decode polyline and add points to list of route coordinates
List<com.google.maps.model.LatLng> coords = points.decodePath();
for (com.google.maps.model.LatLng coord : coords) {
path.add(new LatLng(coord.lat, coord.lng));
}
}
}
}
}
}
}
}
} catch(Exception ex) {
Log.e(TAG, ex.getLocalizedMessage());
}
return path;
}
private List<LatLng> getMarkersEveryNMeters(List<LatLng> path, double distance) {
List<LatLng> res = new ArrayList();
LatLng p0 = path.get(0);
res.add(p0);
if (path.size() > 2) {
//Initialize temp variables for sum distance between points and
//and save the previous point
double tmp = 0;
LatLng prev = p0;
for (LatLng p : path) {
//Sum the distance
tmp += SphericalUtil.computeDistanceBetween(prev, p);
if (tmp < distance) {
//If it is less than certain value continue sum
prev = p;
continue;
} else {
//If distance is greater than certain value lets calculate
//how many meters over desired value we have and find position of point
//that will be at exact distance value
double diff = tmp - distance;
double heading = SphericalUtil.computeHeading(prev, p);
LatLng pp = SphericalUtil.computeOffsetOrigin(p, diff, heading);
//Reset sum set calculated origin as last point and add it to list
tmp = 0;
prev = pp;
res.add(pp);
continue;
}
}
//Add the last point of route
LatLng plast = path.get(path.size()-1);
res.add(plast);
}
return res;
}
}
Conclusion
You can see a result of sample code in the following screenshot
The sample project can be found on GitHub:
https://github.com/xomena-so/so47784512
Do not forget to replace an API key with your's.
I hope this helps!

How to Copy LatLng ArryList To Another LatLng ArryList

I have 2 LatLng Lists
List<LatLng> PairOfLatLong = new ArrayList<LatLng>();
List<LatLng> FakePairOfLatLong = new ArrayList<LatLng>();
Adding LatLng Here
PairOfLatLong.add(pLatLng);
But In Somewhere i want to copy PairOfLatLong in FakePairOfLatLong
I try this way but error occur
FakePairOfLatLong= (ArrayList<LatLng>) PairOfLatLong.clone();
you could use
List<LatLng> FakePairOfLatLong = new ArrayList<LatLng>(PairOfLatLong);
or
FakePairOfLatLong.addAll(PairOfLatLong);

Draw polyline snap to road Android google maps app

I'm currently developing an android google maps app help to get direction between 2 points on the map. I'm able to get the response from google maps service (Direction API) and draw polyline (Google Maps Android SDK) base on list of steps but the line is not snap to the road (curved line stick to road on the map), it's just straight line.
How can I draw polyline snap to road in Android app? I'm using Android Studio.
Here is my code to draw polyline.
void updateMapDirection() {
Polyline newPolyline;
PolylineOptions options = new PolylineOptions().width(3).color(Color.BLUE).geodesic(true);
LatLng latLng = new LatLng(mLegs.get(0).getmStartLocation().getmLatitude(),
mLegs.get(0).getmStartLocation().getmLongitude());
options.add(latLng);
for (WNStep i : mLegs.get(0).getmSteps()) {
latLng = new LatLng(i.getmEndLocation().getmLatitude(), i.getmEndLocation().getmLongitude());
options.add(latLng);
}
newPolyline = map.addPolyline(options);
}
Thanks for your help.
This is how you can do it:
Once you have your JSON object as "result". Parse it, Also decode the polyline in form of a List.
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes
.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
Finally add Polyline Option by looping over the list and setting the properties of your polyline corresponding to the road you want to show as retrieved from Direction API on Google Maps.
PolylineOptions options = new PolylineOptions().width(5).color(Color.BLUE).geodesic(true);
for (int z = 0; z < list.size(); z++) {
LatLng point = list.get(z);
options.add(point);
}
line = myMap.addPolyline(options);

Unable to see multiple marker on google Map

I want to show multiple markers on a google map. My latlng coordinates are fetched from a Parse database but I am not able see marker.
My second problem is that I want to show a title that is Restaurant Name with marker, how can I do this?
This is my code:
private class putMarker extends AsyncTask> {
#Override
protected ArrayList doInBackground(Void... params) {
// TODO Auto-generated method stub
try {
Toast.makeText(getApplicationContext(),
longitude + " " + latitude, Toast.LENGTH_SHORT).show();
ParseQuery query = new ParseQuery(
"Details");
ParseGeoPoint myGeoPiont = new ParseGeoPoint(latitude,
longitude);
query.whereNear("location", myGeoPiont);
query.setLimit(10);
ob = query.find();
for (ParseObject resObj : ob) {
ParseGeoPoint location = resObj
.getParseGeoPoint("location");
restaurantName = (String) resObj.get("RestaurantName");
LatLng resLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
Toast.makeText(getApplicationContext(),
restaurantName, Toast.LENGTH_SHORT)
.show();
PiontList.add(resLatLng);
}
} catch (Exception e) {
// TODO: handle exception
}
return PiontList;
}
protected void onPostExecute(ArrayList latlngList) {
for(LatLng res: latlngList)
{
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res);
markerOptions.icon(BitmapDescriptorFactory
.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);
}
}
}
Please help me out.
it might due to unreachability of googleMap object in onPostExecute() .
Please ensure that googleMap is declared globally.
if possible please paste whole code for better evaluation
Try this
// Create lat long points
Latlng[] point_new = new LatLng[8];
point_new[0] = new LatLng(31.5301843, 74.3207487);
point_new[1] = new LatLng(31.5214693,74.3236027);
point_new[2] = new LatLng(31.5194393, 74.3257327);
point_new[3] = new LatLng(31.4942166, 74.3004533);
point_new[4] = new LatLng(31.4864646, 74.2911203);
point_new[5] = new LatLng(31.4803596, 74.2787933);
point_new[6] = new LatLng(31.4764716, 74.2638203);
point_new[7] = new LatLng(31.4775236, 74.2628873);
// Add markers
for (int i = 0; i < point_new.length; i++) {
MarkerOptions markerOptions = new MarkerOptions()
.position(point_new[i]);
marker = mMap.addMarker(markerOptions);
marker.setTitle("Points");
marker.setSnippet("Distance = 9.6 km, Time = 20 minute/s");
marker.setIcon(BitmapDescriptorFactory.fromResource(R.drawable.p));
}
// Set camera to last point with Zoom level 9
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(point_new[7], 9));
I see a few problems here.
As #Raghunandan mentioned, you cannot update the UI from doInBackground() so you cannot add markers from there. You can however, make your MarkerOptions objects here, and then attach them to the GoogleMap in your postExecute/or in the Activity that hosts the Google Maps.
In your onPostExecute(), you have not set any Title, or Snippet to your markers. Whenever you are creating your marker, make sure to set your title. Then when the user clicks on the marker, the default behavior shows your rest name as a title.
Code will be something like this(as also mentioned by #Inzimam Tariq IT :
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(res)
.setTitle(restaurantName)
.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
googleMap.addMarker(markerOptions);

Categories

Resources