Draw polyline snap to road Android google maps app - android

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);

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();
}

How to calculate distance between two marker points in android

I am creating an android app which shows distance and duration of two marker points in the Map. In the onCreate() I have written the following code:
In MapsActivity.java
private List<LatLng> getDirectionPolylines(List<RouteObject> routes){
List<LatLng> directionList = new ArrayList<LatLng>();
for(RouteObject route : routes){
List<LegsObject> legs = route.getLegs();
for(LegsObject leg : legs){
String routeDistance = leg.getDistance().getText();
String routeDuration = leg.getDuration().getText();
setRouteDistanceAndDuration(routeDistance, routeDuration);
List<StepsObject> steps = leg.getSteps();
for(StepsObject step : steps){
PolylineObject polyline = step.getPolyline();
String points = polyline.getPoints();
List<LatLng> singlePolyline = decodePoly(points);
for (LatLng direction : singlePolyline){
directionList.add(direction);
}
}
}
}
return directionList;
}
I am not clear how to calculate distance & duration in 'getText' in the code above. I was not able to see some APIs like Distancebetween() which is using LtnLtg as references.
Please suggest how to calculate the distance and duration values.
var lat = marker.getPosition().lat();
var lng = marker.getPosition().lng();

Android put marker on start and end of polyline

Hi I am using Async task to grab longitude and latitude in an JSONArray. I am able to draw polyline but I cannot figure out how to draw put in the start and the end of the polyline.
// Initialization
ArrayList<LatLng> polylines = new ArrayList<LatLng>();
JSONArray lines = null;
JSONObject jsonPolyline;
LatLng polyline;
And here is what I have on the onPostExecute of my AsyncTask
lines = json.getJSONArray("track");
for (int i = 0; i < lines.length(); i++) {
jsonPolyline = lines.getJSONObject(i);
polyline = new LatLng(Double.valueOf(jsonPolyline.getString("lat")),
Double.valueOf(jsonPolyline.getString("lon")));
polylines.add(polyline);
}
/*call the polyline */
myMap.addPolyline(new PolylineOptions().addAll(polylines).width(2.0f).color(Color.GREEN));
I tried using , ListIterator but since my Arraylist is <latlng> , I cannot get the first and last element on the arraylist.
How can I get the first and last element on my arraylist so that I can draw marker on the start and end position.
Every Java List<> implements get() and size() methods:
first = polylines.get(0);
last = polylines.get(polyline.size() -1);

Adding multiple points in map using polyline and arraylist

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
)

How can i access all marker on my GoogleMap-Object (android maps v2) and set them (in)visible?

i am currently trying to implement an ActionBar-Button that on usage sets all my markers on my GoogleMap-object visible or invisible. My problem is that i don't know how i can get a reference to all my markers once they have been created and are shown on my map. Im looking for a solution where i stash all my marker-objects into an array, that i can access in other parts of my code aswell. is this approach reasonable?
here is what i am thinking of:
private Marker[] mMarkerArray = null;
for (int i = 0; i < MainActivity.customers.size(); i++) {
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}
and set all my markers invisible on within another method:
for (int i = 0; i < mMarkerArray.length;; i++) {
mMarkerArray[i].setVisible(false);
}
it refuses to add the markers to a Marker[]-array. how can i achieve it?
mMarkerArray.add(marker) doesnt work
i figured out an answer that also regards my customerList having customers without coordinates --> (0,0;0,0). inspired by this blog.
initialize ArrayList:
private ArrayList<Marker> mMarkerArray = new ArrayList<Marker>();
add marker to my map and to the mMarkerArray:
for (int i = 0; i < MainActivity.customers.size(); i++) {
Customer customer = MainActivity.customers.get(i);
if (customer.getLon() != 0.0) {
if (!customer.isProspect()) {
Data mData= new Data(customer.getLat(),customer.getLon(),customer.getName(),
customer.getOrt());
LatLng location = new LatLng(mData.lat, mData.lng);
Marker marker = mMap.addMarker(new MarkerOptions().position(location)
.title(mData.title)
.snippet(mData.snippet));
mMarkerArray.add(marker);
}}}
set all markers not-visible
for (Marker marker : mMarkerArray) {
marker.setVisible(false);
//marker.remove(); <-- works too!
}
Replace
private Marker[] mMarkerArray = null;
with
private List<Marker> mMarkerArray = new ArrayList<Marker>();
and you should be fine.
If you use Android Maps Extensions, you can simply iterate over all markers using
for (Marker marker : googleMap.getMarkers()) {
marker.setVisible(false);
}
without having your own List of all Markers.
You can keep a Collection of OverlayItem within your Activity or Fragment and then call MapView.getOverlays().clear() to make them "invisible" and then add them back to make them visible again. Call MapView.invalidate() after each action to cause the map to be repainted.

Categories

Resources