I am following a tutorial here https://code.google.com/p/osmbonuspack/wiki/Tutorial_1 but I have encountered an error that it doesn't show the correct route correctly. It just shows a straight line from Point A to Point B.
What I want to achieve is to show the correct route from these points. I'm guessing the error is that it doesn't recognize any nodes to go through.
A similar question has been also asked and I am assuming I have the same problem if I haven't explained my question well.
Similar question can be found here: OSMDroid Routing problems when following a tutorial
Here is a part of my code using RoadManager
Here is a part of the code.
try {
//get current longlat
gpsLocator.getLocation();
cur_loc_lat =gpsLocator.getLatitude();
cur_loc_long =gpsLocator.getLongitude();
} catch (Exception e) {
// TODO: handle exception
}
//--- Create Another Overlay for multi marker
anotherOverlayItemArray = new ArrayList<OverlayItem>();
anotherOverlayItemArray.add(new OverlayItem(
"UST", "UST", new GeoPoint( testlat, testlong)));
//--- Create Another Overlay for multi marker
anotherOverlayItemArray.add(new OverlayItem(
locDefine[0], "UST", new GeoPoint( sel_latitude, sel_longitude)));
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
TomWalks.this, anotherOverlayItemArray, myOnItemGestureListener);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
//---
//Add Scale Bar
ScaleBarOverlay myScaleBarOverlay = new ScaleBarOverlay(TomWalks.this);
myOpenMapView.getOverlays().add(myScaleBarOverlay);
try {
//1 Routing via road manager
RoadManager roadManager = new MapQuestRoadManager();
roadManager.addRequestOption("routeType=pedestrian");
/*
roadManager.addRequestOption("units=m");
roadManager.addRequestOption("narrativeType=text");
roadManager.addRequestOption("shapeFormat=raw");
roadManager.addRequestOption("direction=0");
*/
//Then, retrieve the road between your start and end point:
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
waypoints.add(new GeoPoint(testlat, testlong));
waypoints.add(new GeoPoint(sel_latitude,sel_longitude)); //end point
Road road = roadManager.getRoad(waypoints);
// then, build an overlay with the route shape:
PathOverlay roadOverlay = RoadManager.buildRoadOverlay(road, myOpenMapView.getContext());
roadOverlay.setColor(Color.GREEN);
//Add Route Overlays into map
myOpenMapView.getOverlays().add(roadOverlay);
myOpenMapView.invalidate();//refesh map
final ArrayList<ExtendedOverlayItem> roadItems =
new ArrayList<ExtendedOverlayItem>();
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes =
new ItemizedOverlayWithBubble<ExtendedOverlayItem>(TomWalks.this, roadItems, myOpenMapView);
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
int nodesize=road.mNodes.size();
double length = road.mLength;
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
Toast.makeText(TomWalks.this, " Distance : " + length + " Nodes : "+nodesize ,Toast.LENGTH_SHORT).show();
for (int i=0; i<road.mNodes.size(); i++)
{
RoadNode node = road.mNodes.get(i);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem("Step "+i, "", node.mLocation, TomWalks.this);
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
roadNodes.addItem(nodeMarker);
nodeMarker.setDescription(node.mInstructions);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
Drawable icon = getResources().getDrawable(R.drawable.marker_node);
nodeMarker.setImage(icon);
}//end for
myOpenMapView.getOverlays().add(roadNodes);
myOpenMapView.invalidate();//refesh map
} catch (Exception e) {
// TODO: handle exception
Toast.makeText(TomWalks.this,e.getMessage(),Toast.LENGTH_SHORT).show();
}
myMapController.setCenter(new GeoPoint( sel_latitude, sel_longitude));
} catch (Exception e) {
// TODO: handle exception
}
}
}
}//===================================================================================================
Let's try to provide a complete answer to this quite frequent question.
Basically, when you get the "straight line", it means that the RoadManager got an error.
So, first of all, in your code, you should check the result of getRoad, this way:
if (road.mStatus != Road.STATUS_OK){
//handle error... warn the user, etc.
}
Now, where this error is coming from?
=> You must search in the logcat. You should find the full url that has been sent, and probably a stacktrace about the error.
I strongly recommend that you copy/paste this full url in a browser , and check the result.
Here are the typical errors, by decreasing probability:
1) You didnt' read carefully the "Important note" at the beginning of the Tutorial_0, and you are trying to do a Network call in the main thread, with an SDK >= 3.0.
=> Read this "Important note".
2) You asked for a route that is not possible (really not possible, or because of weird positions, or because of setting unsupported options).
=> This is easy to check by copy/pasting the full url in a web browser, and looking at the answer.
3) Your device has no network connectivity.
4) The routing service changed its API (this happened, more than once...).
=> Could be checked by copy/pasting the full url in a browser.
In this case, raise an Issue in OSMBonusPack project, so that we can take it into account ASAP.
5) The routing service is down.
=> Easy to check by copy/pasting the full url in a browser.
I think it is better to use AsyncTasks in this case:
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
RoadManager roadManager = new OSRMRoadManager();
return roadManager.getRoad(waypoints);
}
#Override
protected void onPostExecute(Road result) {
road = result;
// showing distance and duration of the road
Toast.makeText(getActivity(), "distance="+road.mLength, Toast.LENGTH_LONG).show();
Toast.makeText(getActivity(), "durée="+road.mDuration, Toast.LENGTH_LONG).show();
if(road.mStatus != Road.STATUS_OK)
Toast.makeText(getActivity(), "Error when loading the road - status="+road.mStatus, Toast.LENGTH_SHORT).show();
Polyline roadOverlay = RoadManager.buildRoadOverlay(road,getActivity());
map.getOverlays().add(roadOverlay);
map.invalidate();
//updateUIWithRoad(result);
}
}
then call it new UpdateRoadTask().execute(waypoints);
new Thread(new Runnable()
{
public void run()
{
RoadManager roadManager = new OSRMRoadManager();
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>();
GeoPoint startPoint = new GeoPoint(source_lat, source_longi);
waypoints.add(startPoint);
GeoPoint endPoint = new GeoPoint(desti_lat,desti_longi);
waypoints.add(endPoint);
try
{
road = roadManager.getRoad(waypoints);
}
catch (Exception e)
{
e.printStackTrace();
}
runOnUiThread(new Runnable()
{
public void run()
{
if (road.mStatus != Road.STATUS_OK)
{
//handle error... warn the user, etc.
}
Polyline roadOverlay = RoadManager.buildRoadOverlay(road, Color.RED, 8, context);
map.getOverlays().add(roadOverlay);
}
});
}
}).start();
And i am use two jar files 1)slf4j-android-1.5.8.jar and 2)osmdroid-android-4.2.jar and osmbonuspack library.
A strange error I found regarding this is as follows:
Firstly I mention following line of code for taking directions for the vehicle "BIKE"
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_BIKE);
Now when it was first called it follows the following URL:
https://routing.openstreetmap.de/routed-car/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
Now when calling the second time{same MEAN_BY_BIKE}, it is following this URL:
:https://routing.openstreetmap.de/routed-bike/route/v1/driving/68.8889678000,23.2151582000;73.1808008000,22.3110728000?alternatives=false&overview=full&steps=true
So the issue is that no response is for the "routed-bike" and it is calling automatically itself when called for second time.
So as a solution I changed my code to the following:
((OSRMRoadManager) roadManager).setMean(OSRMRoadManager.MEAN_BY_CAR);
You can check your LogCat for the same.
Related
Please look at my code to create layer from geojson string and add layer to map:
private GeoJsonLayer createLayerFromGeojson(String json)
{
JSONObject ob = null;
try
{
ob = new JSONObject(json);
}
catch (JSONException e)
{
e.printStackTrace();
}
GeoJsonLayer layer = new GeoJsonLayer(googleMap, ob);
layer.addLayerToMap();
layer.setOnFeatureClickListener(feature -> Utils.showMessage(getActivity(), "Clicked", feature.getProperty("description").toString()));
return layer;
}
Next add 2 layers to map:
String json = /*first geojson string here*/
String json2 = /*another geojson string here*/
createLayerFromGeojson(json);
createLayerFromGeojson(json2);
Problem: When I click on marker or pologon, always description taken from second json (json2) is displayed, even if I click on object created from first json, on first layer.
What's wrong? Any ideas?
If you check the documentation for the method setOnFeatureClickListener it says:
Sets a single click listener for the entire GoogleMap object, that will be called with the corresponding Feature object when an object on the map (Polygon, Marker, Polyline) is clicked.
To me, it seems silly that we cannot have multiple layers with information from different GeoJson. It needs to be a MultiPolygon, MultiLineString or MultiPoint.
Reference: https://github.com/googlemaps/android-maps-utils/blob/master/library/src/com/google/maps/android/data/Layer.java#L89
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/
I want to get route between two locations,for that i have found esri sample service i.e :http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World.
But if i use this service i am getting error as Unauthorized access to a secure.
I am unable to use this service,Please tell me if any free service for getting route on arcgis map
Thanks.
my code:
public void getRouteFromSource(Geometry current_location,Geometry destination_point,boolean isCurrentLocation){
routeLayer = new GraphicsLayer();
mMapView.addLayer(routeLayer);
// Initialize the RouteTask
try {
String routeTaskURL = "http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World";
mRouteTask = RouteTask.createOnlineRouteTask(routeTaskURL, null);
} catch (Exception e1) {
e1.printStackTrace();
}
// Add the hidden segments layer (for highlighting route segments)
hiddenSegmentsLayer = new GraphicsLayer();
mMapView.addLayer(hiddenSegmentsLayer);
QueryDirections(current_location, destination_point,isCurrentLocation);
}
private void QueryDirections(final Geometry sourceGeometry, final Geometry destinationGeometry,boolean isCurrentLocation) {
// Show that the route is calculating
if(isCurrentLocation==false){
dialog = ProgressDialog.show(mContext, PollingStationLocatorContant.plase_wait,
"Calculating route...", true);
}
// Log.e("mLocation", "mLocation "+sourceGeometry);
// Log.e("POINTTT", "POINTTT"+p);
// Spawn the request off in a new thread to keep UI responsive
Thread t = new Thread() {
private RouteResult mResults;
#Override
public void run() {
try {
// Start building up routing parameters
/*Point startPoint = new Point(78.4867, 17.3850);
Point stopPoint = new Point(79.5941, 17.9689);*/
// Log.e("mLocation.getX()",""+ p.getX()+"---"+ p.getY());
// Log.e("mLocation.getY()",""+ mLocation.getX() +"----"+ mLocation.getY());
//Point startPoint = new Point(mLocation.getX(), mLocation.getY());
//Point stopPoint = new Point(p.getX(), p.getY());
StopGraphic point1 = new StopGraphic(sourceGeometry);
StopGraphic point2 = new StopGraphic(destinationGeometry);
Log.e("point1", ""+point1);
Log.e("point2", ""+point2);
NAFeaturesAsFeature rfaf = new NAFeaturesAsFeature();
// Convert point to EGS (decimal degrees)
// Create the stop points (start at our location, go
// to pressed location)
rfaf.setFeatures(new Graphic[] { point1, point2 });
rfaf.setCompressedRequest(true);
// RouteParameters r = new RouteParameters();
RouteParameters rp = mRouteTask.retrieveDefaultRouteTaskParameters();
//rp.setImpedanceAttributeName("Length");
rp.setReturnDirections(false);
// Assign the first cost attribute as the impedance
rp.setStops(rfaf);
// Set the routing service output SR to our map
// service's SR
rp.setOutSpatialReference(mMapView.getSpatialReference());
//rp.setImpedanceAttributeName("");
// Solve the route and use the results to update UI
// when received
mResults = mRouteTask.solve(rp);
List<Route> routes = mResults.getRoutes();
Route mRoute = routes.get(0);
Geometry routeGeom = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(routeGeom, new SimpleLineSymbol(Color.BLUE,5));
//SimpleMarkerSymbol sls = new SimpleMarkerSymbol(Color.RED, 10,STYLE.CIRCLE);
PictureMarkerSymbol pls=new PictureMarkerSymbol(mContext.getResources().getDrawable(R.drawable.animation_image));
mMapView.setExtent(routeGeom, 20);
Graphic destinatonGraphic = new Graphic(sourceGeometry, pls);
mGraphicsLayer.addGraphic(symbolGraphic);
mDestinationGraphicLayer.addGraphic(destinatonGraphic);
mMapView.addLayer(mGraphicsLayer);
mMapView.addLayer(mDestinationGraphicLayer);
mHandler.post(mUpdateResults);
} catch (Exception e) {
mDestinationGraphicLayer.removeAll();
noRouteFound=true;
e.printStackTrace();
mHandler.post(mUpdateResults);
}
}
};
// Start the operation
t.start();
}
void updateUI() {
if(dialog!=null && dialog.isShowing()){
dialog.dismiss();
if(noRouteFound){
Toast.makeText(mContext, "Unable to find route.Please select with in State", Toast.LENGTH_LONG).show();
}
}
}
Disregarding geocoding services (which may be called for free if data is not stored) routing services do require a token.
As stated in the documentation:
Required parameters: token
Use this parameter to specify a token that provides the identity of a
user that has the permissions to access the service. Accessing
services provided by Esri provides more information on how such an
access token can be obtained.
What you can do is to go here and register a free developer account. You will receive a free token and its related amount of free credits that you can use to query the routing API.
However, the documentation linked above shows samples of response for all possible situations (error, route ok, route not found).
After creating a free developer account follow these steps.
Inside your getRouteFromSource function replace the existing code with this.
TOKEN = "The token you receive after you sign up";
CLIENT_ID = "The client_id you receive after you sign up";
try {
UserCredentials authenticate= new UserCredentials();
authenticate.setUserAccount("your username", "your password");
authenticate.setUserToken(TOKEN, CLIENT_ID);
mRouteTask = RouteTask
.createOnlineRouteTask(
"http://route.arcgis.com/arcgis/rest/services/World/Route/NAServer/Route_World",
authenticate);
} catch (Exception e1) {
e1.printStackTrace();
}
This should solve your problem.
I've been trying very hard to create a route between two points(startPoint, endPoint). But i am getting the following error:
Location "Location 1" in "Stops" is unlocated. Location "Location 2" in "Stops" is unlocated. Need at least 2 valid stops. "Stops" does not contain valid input for any route.
I've posted this question on gis.stackexchange.com and geonet.esri.com and didn't get a reply except one which was not helpful.
My Code:
private final String routeTaskURL = "http://sampleserver3.arcgisonline.com/ArcGIS/rest/services/Network/USA/NAServer/Route";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mMapView = (MapView) findViewById(R.id.map);
mMapView.enableWrapAround(true);
new Thread(new Runnable() {
#Override
public void run() {
try {
UserCredentials userCredentials = new UserCredentials();
userCredentials.setUserToken(token, clientID);
RouteTask routeTask = RouteTask.createOnlineRouteTask(routeTaskURL, userCredentials);
RouteParameters routeParameters = routeTask.retrieveDefaultRouteTaskParameters();
NAFeaturesAsFeature naFeatures = new NAFeaturesAsFeature();
Point startPoint = new Point(36.793653, -119.866896);
Point stopPoint = new Point(36.795488, -119.853345);
StopGraphic startPnt = new StopGraphic(startPoint);
StopGraphic stopPnt = new StopGraphic(stopPoint);
naFeatures.setFeatures(new Graphic[] {startPnt, stopPnt});
routeParameters.setStops(naFeatures);
RouteResult mResults = routeTask.solve(routeParameters);
List<Route> routes = mResults.getRoutes();
System.out.println(mResults.getRoutes());
Route mRoute = routes.get(0);
Geometry geometry = mRoute.getRouteGraphic().getGeometry();
Graphic symbolGraphic = new Graphic(geometry, new SimpleLineSymbol(Color.BLUE, 3));
mGraphicsLayer.addGraphic(symbolGraphic);
System.out.println(mResults.getStops());
} catch (Exception e) {
e.printStackTrace();
}
}
}).start();
}
I've searched the internet. Many developers were/are facing this problem. I've tried all the solutions but none of them worked. I got routeTaskURL from the ArcGIS Routing Sample app. The link which is given in the documentation of ArcGIS maps gives me the 403 error if i open it in the browser.
Note: "token" and "clientID" is declared in the first step and they both are taken from the ArcGIS developers console where i registered my application.
Any Suggestions?
Your X and Y values are switched. Change to this:
Point startPoint = new Point(-119.866896, 36.793653);
Point stopPoint = new Point(-119.853345, 36.795488);
See the Point class documentation to learn that the constructor parameters are (x, y), not (y, x). The route service you're using has a default spatial reference of 4326, which is unprojected longitude and latitude. -119.866896 and -119.853345 are not valid latitude (y) values, but they are valid longitude (x) values.
Is it possible to use it as library project for my application,i want to use Android Google Maps real app search-ability functionality. How can i do it,is it possible?
Thanks in advance..
EDIT:
I have shown Google Map in my app successfully, I want to include Google Map search functionality means that I can able to search any location in the world in auto suggested field and by selecting a particular location and move marker to that location. so how can I?
I tried this and this but not getting auto suggested text why I don't know..
I want like:
step1: show map with search box
step2: while entering text it should auto suggest.
step3: when click on particular name move map to that location
You can easily provide that kind of search functionality by using Places API and Geocode API (Both will help you according to your usecase).
Read the below Documentation for your assistance.
GeoCode API
Places API
I would recommend to use Places API for your need ( As per my observation on your usecase). But you could also use geocode, If you needed.
Many working reference and examples are there.
For startup, below are my reference :
PlacesAPI AutoComplete feature, Hotel Finder with Autocomplete
GeocodeAPI Simple GeoCoding
NOTE :
I have suggested javascript API. But not sure whether it will help you in Android environment (I dont know anything about android environment).
No single Api can help you have to use multiple google api's
Step1. Implement Google Place autocomplete Read this
Step2. You have to geocode means you have to convert address to latitude and longitude check this
Step3. Now You can plot these lat-long on the map.
This works for me.
I think you should take a look at the Google Maps API for Android at https://developers.google.com/maps/documentation/android/
The Google Search Appliance doesn't have any mapping or geo search features right now.
This is how I did it ---
Android Manifest file should contain the following lines:
<uses-library
android:name="com.google.android.maps"
android:required="true" >
</uses-library>
<!-- You must insert your own Google Maps for Android API v2 key in here. -->
<meta-data
android:name="com.google.android.maps.v2.API_KEY"
android:value="<put your api key value here>" />
Location XML file should have the following apart from anything extra:
<fragment
android:name="com.google.android.gms.maps.SupportMapFragment"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
Location java file should have something like this:
View mapView = null;
private GoogleMap mMap;
mMap = supportMapFragment.getMap();
mapView = (View) view.findViewById(R.id.map);
SupportMapFragment supportMapFragment = (SupportMapFragment) fragmentManager
.findFragmentById(R.id.map);
if(mMap != null){
mMap.setMyLocationEnabled(true);
}
if(mMap != null)
mMap.setOnMapLongClickListener(new GoogleMap.OnMapLongClickListener() {
#Override
public void onMapLongClick(LatLng latLng) {
new EditMap().execute("", String.valueOf(latLng.latitude), String.valueOf(latLng.longitude));
}
});
class EditMap extends AsyncTask<String, String, String> {
/**
* Before starting background thread Show Progress Dialog
* */
#Override
protected void onPreExecute() {
super.onPreExecute();
}
/**
* getting Albums JSON
* */
protected String doInBackground(String... args) {
String address = args[0];
double latitude = Double.parseDouble(args[1]);
double longitude = Double.parseDouble(args[2]);
return editMap(address, latitude, longitude);
}
/**
* After completing background task Dismiss the progress dialog
* **/
protected void onPostExecute(String result) {
if(!result.equals(""))
ToastUtil.ToastShort(getActivity(), result);
else {
mMap.clear();
mMap.addMarker(new MarkerOptions().position(new LatLng(lat, lng)).title(attvalue));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(lat, lng), 11));
}
}
}
NOTE:
These are the minimal requirements for the setting of location as you choose from Map that fills the location in your text.
There is a background thread that runs as you long press the location in a map.
The listener defined for that is setOnMapLongClickListener as you see above.
The execution will place the marker to the exact location you chose to mark as set.
There will be a done button after you have chosen the location by a marker. This done button will confirm what you have chosen and will set that on a textfield for you.
The above code uses the method editMap to edit the map location.
The implementation is as done here:
private String editMap(String address, double latitude, double longitude ) {
String keyword = null;
try {
Geocoder geocoder = new Geocoder(getActivity(), Locale.getDefault());
if(!address.equals("")){
keyword = address;
java.util.List<android.location.Address> result = geocoder
.getFromLocationName(keyword, 1);
if (result.size() > 0) {
lat = (double) result.get(0).getLatitude();
lng = (double) result.get(0).getLongitude();
attvalue = address;
} else {
return "Record not found";
}
} else {
String sUrl = "http://google.com/maps/api/geocode/json?latlng="+latitude+","+longitude+"&sensor=true";
DefaultHttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(sUrl);
HttpResponse r = client.execute(get);
int status = r.getStatusLine().getStatusCode();
if(status == 200){
HttpEntity e = r.getEntity();
String data = EntityUtils.toString(e);
try{
JSONObject jsonObject = new JSONObject(data);
JSONArray results = jsonObject.getJSONArray("results");
JSONObject addressObject = results.getJSONObject(0);
JSONArray addressComp = addressObject.getJSONArray("address_components");
String city = "", state = "";
for(int i=0; i < addressComp.length(); i++){
JSONArray types = addressComp.getJSONObject(i).getJSONArray("types");
if(city.equals("") && types.getString(0).equals("locality"))
city = addressComp.getJSONObject(i).getString("long_name");
if(state.equals("") && types.getString(0).equals("administrative_area_level_1"))
state = addressComp.getJSONObject(i).getString("long_name");
if(!city.equals("") && !state.equals(""))
break;
}
attvalue = city + ", " + state;
} catch (JSONException e1) {
e1.printStackTrace();
}
lat = latitude;
lng = longitude;
}else{
return "Location Not Found";
}
}
} catch (IOException io) {
return "Connection Error";
}
return "";
}
I hope this is enough to help you out.