{
"type":"FeatureCollection",
"generator":"JOSM",
"features":[
{
"type":"Feature",
"properties":{
},
"geometry":{
"type":"LineString",
"coordinates":[
[
121.54821846780,
24.98741107673
],
[
121.54812039953,
24.98739360280
],
[
121.54812750162,
24.98736155308
],
[
121.54813477853,
24.98732871440
],
[
121.54814403650,
24.98728693577
]
]
}
},
{
"type":"Feature",
"properties":{
},
"geometry":{
"type":"LineString",
"coordinates":[
[
121.54813477853,
24.98732871440
],
[
121.54819734540,
24.98733966151
],
[
121.54819365737,
24.98735561598
]
]
}
},
{
"type":"Feature",
"properties":{
},
"geometry":{
"type":"LineString",
"coordinates":[
[
121.54812750162,
24.98736155308
],
[
121.54780189872,
24.98730374867
],
[
121.54776282754,
24.98729681235
]
]
}
}
]
this is Geojson path,how could I draw two point,and the route will follow this path?
I used JOSM to draw.
if (route == true) {
start = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(point.getLatitude(), point.getLongitude())).title("start").icon(icon));
route = false;
} else {
if(destination!=null){
mapboxMap.removeMarker(destination);
}
destination = mapboxMap.addMarker(new MarkerOptions().position(new LatLng(point.getLatitude(), point.getLongitude())).title("finish"));
LatLng[] points = new LatLng[2];
LatLng loc = new LatLng(start.getPosition());
LatLng dest = new LatLng(destination.getPosition());
points[0] = loc;
points[1] = dest;
if (poly != null) {
mapboxMap.removePolyline(poly);
}
poly = mapboxMap.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#3887be"))
.width(5));
}
the route is straight line,I want route draw on my Geojson path,how can i do?
I want the two marker follow my path to plan the best path,I can load the Geojson path on Android and draw the path on map,but how do i let the two point follow my path to creat the route? thanks!
Try this code for making a route along your path:
mMap = googleMap;
mMap.addPolyline(new PolylineOptions().add(
new LatLng(Longitude,Latitude),
new LatLng(Longitude,Latitude), // add many as you want
)
.width(10)
.color(Color.Red)
);
For two random points on map, try the answer given here
Get location of clicked point
This is an example of single marker(Source) but you can store these values in temp variables and can get another marker(Dest.). After getting both the points, you can create a path between them using Polyline.
First check you got proper GeoJson. Then for draw direction use below method.
If you found proper then get waypoint array from response by using this code:
List<DirectionsRoute> route = response.body().getRoutes().get(0).getGeometry().getWaypoints();
Pass this waypoint array to below method. It will use AsyncTask for draw a polyline.
public void drawDirection(List<DirectionsRoute> route) {
map.clear();
map.addMarker(new MarkerOptions()
.title("Destination")
.snippet("Distance: "+String.valueOf(route.get(0).getDistance()/1000))
.position(destLatlng));
new DrawGeoJson().execute(route);
}
Below is AsyncTask for draw polyline with multiple route (if possible) with multiple color.
private class DrawGeoJson extends AsyncTask<List<DirectionsRoute>,String,List<List<LatLng>>>
{
#Override
protected void onPreExecute() {
}
#Override
protected List<List<LatLng>> doInBackground(List<DirectionsRoute>... params) {
List<List<LatLng>> pointsArray =new ArrayList<>();
List<LatLng> points = new ArrayList<>();
String jsonResponse= getString(R.string.jsonResponse);
String ch=jsonResponse.substring(95,110);
Log.d("Char",String.valueOf(ch));
try {
List<DirectionsRoute> routeList=params[0];
//If more than one route available then this loop will iterate for every route.
for(int i=0;i<routeList.size();i++) {
points=new ArrayList<>();
DirectionsRoute route = params[0].get(i);
for (List<Double> doubleList : route.getGeometry().getCoordinates()) {
LatLng latLng = new LatLng(doubleList.get(1), doubleList.get(0));
points.add(latLng);
}
pointsArray.add(points);
}
} catch (Exception exception) {
Log.e("LOG", "Exception Loading GeoJSON: " + exception.toString());
exception.printStackTrace();
}
return pointsArray;
}
#Override
protected void onPostExecute(List<List<LatLng>> pointsArray) {
super.onPostExecute(pointsArray);
if(pointsArray.size()>0) {
int[] rainbow=MainActivity.this.getResources().getIntArray(R.array.rainbow);
for(int i=0;i<pointsArray.size();i++) {
int colorForPolyline;
if(i>rainbow.length){
colorForPolyline=i%7;
}else{
colorForPolyline=i;
}
if (pointsArray.get(i).size() > 0) {
map.addPolyline(new PolylineOptions()
.addAll(pointsArray.get(i))
.color(rainbow[colorForPolyline])
.width(4));
}
}
}
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(sourceLatlng) // Sets the center of the map to Maracanã
.bearing(0) // Sets the orientation of the camera to look west
.tilt(20) // Sets the tilt of the camera to 30 degrees
.build(); // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition), 3000, null);
}
}
Related
i am creating a user tracker project , and what i want to do is to draw the user path on the map , the method that i used it's Polyline and this is the code
public void drawOnMap(ArrayList<LatLng> directionPoints) {
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.GREEN).geodesic(false);
rectLine.addAll(directionPoints);
mMap.addPolyline(rectLine);
}
but after about 500 polyline the map going to laggy and after 1900 the app crash
so is there is better solution
i found a solution and this is the right code
private Polyline polyline;
public void drawOnMap(ArrayList<LatLng> directionPoints) {
if(polyline == null)
{
PolylineOptions rectLine = new PolylineOptions().width(5).color(Color.GREEN).geodesic(false);
rectLine.addAll(directionPoints);
polyline = mMap.addPolyline(rectLine);
}else{
polyline.setPoints(directionPoints);
}
}
I'm trying to draw a polyline from what the Google Directions Api returns, the api has this field, overview_polyline, I'm assuming that this field contains the entire polyline so I was thinking why not draw the polyline from there, this is what I have in my JSON, from Google:
{
geocoded_waypoints: [
{},
{}
],
routes: [
{
bounds: {},
copyrights: "Dados do mapa ©2017 Google, Inst. Geogr. Nacional",
legs: [],
overview_polyline: {
points: "cxwnFtdct#dAQlAf#fAf#|Aq#l#]pCcFhCjA|LfJlAT~#IpDi#jAb#f#HXi#t#kBhBeBx#Qz#z#dClHzFpW`H|RvTpj#`AxAdBdAnAXhB?fBk#rAcAnG_HhCgAjAKrATbA`Al#lBHnAc#rFgBhIkCxMBfIlBvHnBtCnB|AnEdCrJxFj#fB#h#OhAgCtHGfCl#jAlA\jE]tDBzBb#tLxFtK~E`d#hShIzEtDhDxDrEfDpFlFjNvDtRdDjThF`TzH`QhEhG|EvFhL`JpJtE|LpEdOpFjOzGlPfJlHzE~NjLfQvPfP|RtHrKxDjGfI|NdHbOvGjPfCbHpCtIvJh_#vG|[|CtNvFvSvE~MfI|QzLbTfNxQbKlKrRzP|NnNvNlQjIzMnLfV`T|h#nDbHhIdMxFjH~JrMnEfHzIrQfHvOtEjI|MnQfNzP`FzI~EnLrKp[nDlHvErHzL~MbRbM`EjCjFxEtRnX|D~EjIhI~WrRxGlGdFnG`JjNxHzKfTxVfKfRfMbRlErHtBlFxIjYvHnPpBtFxF~WpCjHjGhJfDzClF~CnDlArDl#pC\vHXvX[lOaB|GcBdFqBxQwJbDmAxE_ApJ_#jEXtItBrQ~EbQbDlUfBpMfA|IxCbF`DhGlGnJjKtJrF`SpFbRnDdUxAbGrAlEjBnFpDtNnMfGlE~[lTbRdQjTpUxH`GjHfEnGlC`O|DrUxEnEzAfFrBnSpIjPnDxSlAf\lAl~#hDzRrAjOpBvKrBrQtEv^pM``#rPrR|JxSdMlGnGfGtH~HxFdFlBtGfApGp#bG|AnHxD|FzFrH`L~FvH|HrFrFtBtFjA~Mt#pHR|FhA`IfDpEbDzFxGrHrKhEtErF`EnS`MzMvItSdUfF~DtE~B|SrInEnBzDtCxN`QpQfVtQ~Yjn#~fAnK`RvLlRzEjF|GlFrc#vUfRjKfIvGxDhEjIxKdN~T`L~MrFvE~LhIlp#fb#xCtBzFtFbEzFbDrGhH`TfF|JnGfHzEdD|UdIpTdHtKtFj]nUrEzC~[pTfLfG|EbB~KfCnTvDpmAxSzs#~LhOfDzOdFfOxGdY`O`k#zYnVzMlK|HrFjFbXj[rCbCvDfB|FfBbD^xRBlb#nBrIdArJvDfD|B|FzFvFzHnCbIDrCk#dA_A_#q#mHz#sAvAJ^f#r#n#x#UR_#fBGjET`S~#ro#pCpXpAfFp#dEhCnGtE#HXl#n#H^W|ASpShAbZxAtPp#~SjAzGZKdDStBd#x#dC#nEVz#HtAp#b#\OZ|AbBxDnFJf#"
},
summary: "A1",
warnings: [ ],
waypoint_order: [ ]
}
],
status: "OK"
}
How do I draw with that value?
This help me,you can use it..
Firstly create a google server key from google developer account
GoogleDirection.withServerKey(getResources().getString(R.string.SERVER_KEY))
.from(SourceLatlng)
.to(DestinationLatlng)
.execute(new DirectionCallback() {
#Override
public void onDirectionSuccess(Direction direction, String message) {
if (direction.isOK()) {
routeSucess2(direction, message,SourceLatlng,DestinationLatlng);
} else {
//selectedRawLine = ERROR;
}
}
#Override
public void onDirectionFailure(Throwable t) {
t.printStackTrace();
}
});
then draw a route using google direction
private void routeSucess2(Direction direction, String message,LatLng sourceLatlng,LatLng DestinationLng) {
for (Route route : direction.getRouteList()) {
PolylineOptions polyoptions = new PolylineOptions();
polyoptions.color(getResources().getColor(R.color.primary__dark));
polyoptions.width(5);
polyoptions.addAll(route.getOverviewPolyline().getPointList());
poly = googleMap.addPolyline(polyoptions);
poly.setClickable(true);
}
LatLngBounds.Builder latLngBuilder = new LatLngBounds.Builder();
if(sourceLatlng!=null)
latLngBuilder.include(sourceLatlng);
if(DestinationLng!=null)
latLngBuilder.include(DestinationLng);
try {
LatLngBounds bounds = latLngBuilder.build();
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds,
UiHelper.dpToPixel(getActivity(), 135));
googleMap.animateCamera(cu);
} catch (Exception e) {
e.printStackTrace();
}
}
This would help you.
#alb First you should parse lat,long from JSON. You can see this link:
https://developers.google.com/maps/documentation/directions/
Then you have to get lat, long values & put them in List<>.
After that you can use below code for draw polyline on map:
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);
I already have replied on similar question on below link
How to buffer a polyline in Android or draw a polygon around a polyline?
It will resolve your Issue probably
I am using Mapbox (4.2.1) to draw a line from my position to a target position. I have the intention of using the straight line as an extremely basic navigation aid. As such I am re-drawing the guide line OnMyLocationChanged(). However it appears that as my location changes it will draw the line to my new location but MyLocationView (User icon) does not update in accordance (See image below).
They will eventually end up meeting again but it takes some time. It seems that the line is getting drawn inside the accuracy radius, however I would prefer if it could draw the line straight from the user icon.
Is there a simple way to draw a line between the user (The actual icon on the map) and a location which updates as the user moves?
My OnMyLocationChanged is:
MapboxMap.OnMyLocationChangeListener listner = new MapboxMap.OnMyLocationChangeListener(){
#Override
public void onMyLocationChange(final #Nullable Location locationChanged) {
//If we are not targeting anything or we are not tracking location
if(target == null || !map.isMyLocationEnabled()) return;
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(MapboxMap mapboxMap) {
//Log.i("LOC-MAPLINE", "Drawing from mapLoc call");
//Error if we don't have a location
if(!mapboxMap.isMyLocationEnabled() || locationChanged == null) return;
LatLng[] points = new LatLng[2];
final Location myLoc = locationChanged;
LatLng loc = new LatLng(myLoc.getLatitude(), myLoc.getLongitude());
LatLng dest = new LatLng(target.getLatitude(), target.getLongitude());
points[0] = loc;
points[1] = dest;
mapboxMap.removeAnnotations();
loadMarker(target);
PolylineOptions poly = new PolylineOptions()
.add(points)
.color(Color.parseColor("#3887be"))
.width(5);
line = mapboxMap.addPolyline(poly);
}
});
}
};
Any assistance is greatly appreciated, thank you!
EDIT (In regards to possible duplicate question - Google direction route from current location to known location)
I believe my question is different for a few reasons.
I am more concerned on getting the location of the user icon overlay rather than actual location (Accuracy issue)
I am not interested in getting turn for turn directions (Like those from a directions API)
I am using Mapbox rather than google maps (Not too sure but there could be some differences).
Nevertheless that question does not seem to answer my question
According to documentation you need only implement this method passing your currentLocation (origin) and destination
private void getRoute(Position origin, Position destination) throws ServicesException {
MapboxDirections client = new MapboxDirections.Builder()
.setOrigin(origin)
.setDestination(destination)
.setProfile(DirectionsCriteria.PROFILE_CYCLING)
.setAccessToken(MapboxAccountManager.getInstance().getAccessToken())
.build();
client.enqueueCall(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().getRoutes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
// Print some info about the route
currentRoute = response.body().getRoutes().get(0);
Log.d(TAG, "Distance: " + currentRoute.getDistance());
Toast.makeText(
DirectionsActivity.this,
"Route is " + currentRoute.getDistance() + " meters long.",
Toast.LENGTH_SHORT).show();
// Draw the route on the map
drawRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
Toast.makeText(DirectionsActivity.this, "Error: " + throwable.getMessage(), Toast.LENGTH_SHORT).show();
}
});
}
private void drawRoute(DirectionsRoute route) {
// Convert LineString coordinates into LatLng[]
LineString lineString = LineString.fromPolyline(route.getGeometry(), Constants.OSRM_PRECISION_V5);
List<Position> coordinates = lineString.getCoordinates();
LatLng[] points = new LatLng[coordinates.size()];
for (int i = 0; i < coordinates.size(); i++) {
points[i] = new LatLng(
coordinates.get(i).getLatitude(),
coordinates.get(i).getLongitude());
}
// Draw Points on MapView
map.addPolyline(new PolylineOptions()
.add(points)
.color(Color.parseColor("#009688"))
.width(5));
}
reference https://www.mapbox.com/android-sdk/examples/directions/
while loading google map on device i am receiving below screen sometimes.it comes on second load as shown below. otherwise it comes perfectly as normal google map with route I am using SupportmapFragment and get googleMap object as.
supportMapFragment = (SupportMapFragment) getChildFragmentManager().findFragmentById(R.id.map_view_fragment);
below is code for displaying map in activity/fragment
public static void drawRouteIntoMap(final List<? extends MapHelper> position, final GoogleMap googleMap) {
/*List<MapHelper> position = new ArrayList<MapHelper>();
for (int i = lastPosition; i < maps.size(); i++) {
position.add(maps.get(i));
}*/
final LatLngBounds.Builder mapBounds = new LatLngBounds.Builder();
if (position.size() > 0 && Validator.isNotNull(googleMap)) {
googleMap.clear();
List<PolylineOptions> polylineOptionses = new ArrayList<PolylineOptions>();
PolylineOptions option = null;
Boolean lastPause = null;
for (MapHelper map : position) {
if (map.isPause()) {
if (Validator.isNull(lastPause) || !lastPause) {
option = new PolylineOptions().width(5).color(Color.rgb(255, 0, 155)).geodesic(true);
polylineOptionses.add(option);
}
mapBounds.include(new LatLng(map.getLatitude(),map.getLongitude()));
option.add(new LatLng(map.getLatitude(), map.getLongitude()));
} else {
if (Validator.isNull(lastPause) || lastPause) {
option = new PolylineOptions().width(5).color(Color.rgb(0, 179, 253)).geodesic(true);
polylineOptionses.add(option);
}
mapBounds.include(new LatLng(map.getLatitude(),map.getLongitude()));
option.add(new LatLng(map.getLatitude(), map.getLongitude()));
}
lastPause = map.isPause();
}
for (PolylineOptions options : polylineOptionses) {
googleMap.addPolyline(options);
}
if(Validator.isNotNull(option)){
//List<LatLng> points = option.getPoints();
googleMap.setOnMapLoadedCallback(new GoogleMap.OnMapLoadedCallback() {
#Override
public void onMapLoaded() {
LatLng startPoint = new LatLng(position.get(0).getLatitude(), position.get(0).getLongitude());
googleMap.addMarker(new MarkerOptions().position(startPoint).title("start").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN)));
mapBounds.include(startPoint);
LatLng endPoint = new LatLng(position.get(position.size() - 1).getLatitude(), position.get(position.size() - 1).getLongitude());
mapBounds.include(endPoint);
googleMap.addMarker(new MarkerOptions().position(endPoint).title("finish").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));
googleMap.setPadding(15, 205, 10, 110);
googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 0));
//googleMap.animateCamera(CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 10));
googleMap.moveCamera(CameraUpdateFactory.zoomOut());
}
});
}
}
}
supportMapFragment.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
if (Validator.isNotNull(googleMap)) {
googleMap.setMyLocationEnabled(false);
googleMap.clear();
googleMap.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
#Override
public void onMapClick(LatLng latLng) {
if (activity.preferences.isSaveScreen()) {
facebook.setChecked(false);
twitter.setChecked(false);
activity.replaceFragment(new FullMapFragment(), null);
}
if (!activity.preferences.isSaveScreen()) {
activity.preferences.setHistoryScreen(true);
activity.replaceFragment(new FullMapFragment(), null);
}
}
});
if (gps) {
nonGpsSummary.setVisibility(View.GONE);
List<HistoryMap> historyMaps = new ArrayList<HistoryMap>();
if (Validator.isNotNull(activity.preferences.getUserHistory().getHistoryMaps())) {
historyMaps.addAll(Arrays.asList(activity.preferences.getUserHistory().getHistoryMaps()));
}
if (historyMaps.size() > 0) {
if (Validator.isNotNull(googleMap)) {
drawRouteIntoMap(historyMaps, googleMap);
}
} else {
mapFrame.setVisibility(View.GONE);
}
} else {
gpsSummary.setVisibility(View.GONE);
}
}
}
});
this question is in relation with zoom over specific route google map.
by using that i get proper route with mapbounds but i m not getting why this screen is displaying.
i am not receiving cordinates 0.0 i debug that,api key is also proper.
You are calling moveCamera twice. The first one tries to move the camera but the second one doesn't wait for the first one to end and performs the zoom out.
This may not happen all the times and may behave differently on different devices.
The best option is to set a padding on your CameraUpdateFactory.newLatLngBounds(mapBounds.build(), 0) instead of 0
This problem occurs when your coordinates are not properly set. Make sure the coordinates that you are using is pointing in the land to get the maps correctly. Another possible reason is your API key is not working, try to generate new API key for this project.
For more information, check these related SO questions.
Android google maps return error and blue screen
Blue screen in Android Google Maps
previously I use GmapV2 from Android: How to draw route directions google maps API V2 from current location to destination. But now it's not work I got error about that class. How to fix that class?
This code will draw the line from origin to destination.
#Override
public void onDirectionSuccess(Direction direction, String rawBody) {
Log.d("Status", "Success");
Log.d("Direction", "" + direction);
mMap.addMarker(new MarkerOptions().position(origin));
mMap.addMarker(new MarkerOptions().position(destination));
if (waypoints != null){
for (int i = 0; i < waypoints.size(); i++){
mMap.addMarker(new MarkerOptions().position(waypoints.get(i)));
}
}
ArrayList<LatLng> directionPositionList = direction.getRouteList().get(0).getLegList().get(0).getDirectionPoint();
mMap.addPolyline(DirectionConverter.createPolyline(this, directionPositionList, 5, Color.BLUE));
Log.d("Status", "Success 2");
showRoute.setVisibility(View.GONE);
}