Cannot create route from one point to another ArcGIS Android - android

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.

Related

How to fix this problem Collect coordinates to point polygon

I have problem about my gps and plot polygon
I collect GPS every second from
Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
and put it to realm database
(So I things do I not good idea)
Maybe should accumulate every 10 meters
image below is result I got
my problems
Polygon look alike the PASTA instead of area.
My gps can jump over to another building(GPS is not stable)
help recommend me please.
ArrayList<LatLng> coordList = new ArrayList<LatLng>();
#Cleanup Realm realm = Realm.getDefaultInstance();
RealmResults<PolygonAreas> PlotPolygon = realm.where(PolygonAreas.class).findAll();
if (PlotPolygon.size() > 0) {
for (PolygonAreas Polypoint : PlotPolygon) {
coordList.add(new LatLng(Polypoint.getLatitude(), Polypoint.getLongitude()));
try {
Runnable addPolygon = new CellTowerMarkerGoogle.AddPolygon(mMap, new PolygonOptions()
.addAll(coordList).fillColor(0x7F80b370).strokeColor(0x7F80b370)
);
getActivity().runOnUiThread(addPolygon);
} catch (Exception e) {
log.debug("Exception : " + e);
}
}
}
public static class AddPolygon implements Runnable{
private GoogleMap map;
private PolygonOptions options;
public AddPolygon(GoogleMap map,PolygonOptions options){
this.map = map;
this.options = options;
}
#Override
public void run() { map.addPolygon(options);}
}
I found problem
Because my logic incorrect variable addPolygon
every back again it's create new Object polygon(.addAll)
It causes the creation of overloaded objects.
How can I fix it?
I have to destroy the polygon object and recreate it every time.
The value will be updated all the time. I have to destroy and create new polygons every time to update.

How to get sample route arcgis in android?

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.

Google Places Api sort by distance

Currently developing an Android application that returns the closest 20 location to the users current location.
Google Places API is returning ~20 places close to the users location but not the closest 20 sorted by distance.
Looking at the Google Places API Documentation does not show anything that I can see to be incorrect.
GetPlaces.java
String types = "accounting|airport|amusement_park|aquarium|art_gallery|atm|bakery|bank|bar|beauty_salon|bicycle_store|book_store|bowling_alley|bus_station|cafe|campground|car_dealer|car_rental|car_repair|car_wash|casino|cemetery|church|city_hall|clothing_store|convenience_store|courthouse|dentist|department_store|doctor|electrician|electronics_store|embassy|establishment|finance|fire_station|florist|food|funeral_home|furniture_store|gas_station|general_contractor|grocery_or_supermarket|gym|hair_care|hardware_store|health|hindu_temple|home_goods_store|hospital|insurance_agency|jewelry_store|laundry|lawyer|library|liquor_store|local_government_office|locksmith|lodging|meal_delivery|meal_takeaway|mosque|movie_rental|movie_theater|moving_company|museum|night_club|painter|park|parking|pet_store|pharmacy|physiotherapist|place_of_worship|plumber|police|post_office|real_estate_agency|restaurant|roofing_contractor|rv_park|school|shoe_store|shopping_mall|spa|stadium|storage|store|subway_station|synagogue|taxi_stand|train_station|travel_agency|university|veterinary_care|zoo";
resourceURI = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location="+myLocation.latitude+","+myLocation.longitude+"&radius=500&rankBy=distance&types="+ URLEncoder.encode(types, "UTF-8")+"&sensor=true&key=GOOGLE_MAPS_KEY";
try {
String url =resourceURI; //getURL(myLocation.latitude,myLocation.longitude);
HttpParams httpParams = new BasicHttpParams();
HttpConnectionParams.setConnectionTimeout(httpParams, 30000);
HttpConnectionParams.setSoTimeout(httpParams, 30000);
DefaultHttpClient httpClient = new DefaultHttpClient(httpParams);
HttpGet httpGet = new HttpGet(url);
httpGet.setHeader("Content-type", "application/json");
ResponseHandler responseHandler = new BasicResponseHandler();
String response = (String) httpClient.execute(httpGet, responseHandler);
if (response != null) {
mResult = new JSONObject(response);
results = mResult.getJSONArray("results");
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
return null;
}
catch (IOException e) {
e.printStackTrace();
return null;
}
catch (JSONException e) {
e.printStackTrace();
return null;
}
return results;
}
This returns valid JSON, but not the closest places to the passed in distance. I know for a fact that there are closer places than what the request is returning.
For example, I make a request at a known google place, but it is not showing the place I am currently at- but others that are farther.
Maybe you've already solved your problem, but I hope this can help (Focus on what is in bold):
radius - Defines the distance (in meters) Within Which to return Place results. The maximum allowed is 50 000 meters radius. Note That radius must not be included if rankby = distance (Described below under Optional parameters) is specified.
rankby — Specifies the order in which results are listed. Possible values are:
prominence (default). This option sorts results based on their importance. Ranking will favor prominent places within the specified area. Prominence can be affected by a Place's ranking in Google's index, the number of check-ins from your application, global popularity, and other factors.
distance. This option sorts results in ascending order by their distance from the specified location. When distance is specified, one or more of keyword, name, or types is required.
according: https://developers.google.com/places/documentation/search?hl=en
I have understood according to google documentation that you can not simultaneously send arguments "rankby" and "radius", you must use only one of them at the same time, this way you will get the results sorted by distance.
test the request doing this:
resourceURI = "https://maps.googleapis.com/maps/api/place/nearbysearch/json?
location="+myLocation.latitude+","+myLocation.longitude+"&rankBy=distance
&types="+ URLEncoder.encode (types, "UTF-8") + "&sensor = true&
key = GOOGLE_MAPS_KEY";
to see how you do, good luck!
Hope this code will work..
private ArrayList<CLPlaceDTO> sortLocation(LatLng currentLatLng, ArrayList<?> alLocationDTO)
{
ArrayList<CLPlaceDTO> clPlaceDTOArrayList;
ArrayList<CLPlaceDTO> clPlaceDTOArrayList1 = new ArrayList<>();
double dCurrentLat = currentLatLng.latitude;
double dCurrentLong = currentLatLng.longitude;
Iterator<?> clIterator = alLocationDTO.iterator();
while (clIterator.hasNext())
{
clIterator.next();
clPlaceDTOArrayList = new ArrayList<>();
for (int j = 0; j < alLocationDTO.size(); j++)
{
CLLocationDTO clLocationDTO = (CLLocationDTO) alLocationDTO.get(j);
double dLat = clLocationDTO.getLatitude().doubleValue();
double dLng = clLocationDTO.getLongitude().doubleValue();
LatLng clNewLatLng = new LatLng(dLat, dLng);
double dDistance = getDistance(dCurrentLat, dCurrentLong, dLat, dLng);
CLPlaceDTO clPlaceDTO = new CLPlaceDTO(clLocationDTO.getAccountName(), clNewLatLng, dDistance);
clPlaceDTOArrayList.add(clPlaceDTO);
}
Collections.sort(clPlaceDTOArrayList, new CLSortPlaces(currentLatLng));
dCurrentLat = clPlaceDTOArrayList.get(0).getLatlng().latitude;
dCurrentLong = clPlaceDTOArrayList.get(0).getLatlng().longitude;
clPlaceDTOArrayList1.add(clPlaceDTOArrayList.get(0));
clIterator.remove();
}
return clPlaceDTOArrayList1;
}
public static double getDistance(double dbFromLatitude,double dbFromLongitude,double dbToLatitude,double dbToLongitude)
{
double dbRadiusMeters = EARTH_RADIUS * 1000 ; // Earth’s mean radius in meter
double dbLatitudeDiff = Math.toRadians(dbToLatitude - dbFromLatitude);
double dbLongitudeDiff = Math.toRadians(dbToLongitude - dbFromLongitude);
double a = Math.sin(dbLatitudeDiff / 2) * Math.sin(dbLatitudeDiff / 2) +
Math.cos(Math.toRadians(dbFromLatitude)) * Math.cos(Math.toRadians(dbToLatitude)) *
Math.sin(dbLongitudeDiff / 2) * Math.sin(dbLongitudeDiff / 2);
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
double d = dbRadiusMeters * c;
return d; // returns the distance in meter
}
public class CLSortPlaces implements Comparator<CLPlaceDTO>
{
private LatLng currentLoc;
CLSortPlaces(LatLng current)
{
currentLoc = current;
}
#Override
public int compare(final CLPlaceDTO place1, final CLPlaceDTO place2)
{
return (int) (place1.dDistance - place2.dDistance);
}
}
public class CLPlaceDTO
{
public LatLng latlng;
public String sNameOfLocation;
public double dDistance;
public CLPlaceDTO(String sNameOfLocation, LatLng latlng,double dDistance)
{
this.sNameOfLocation = sNameOfLocation;
this.latlng = latlng;
this.dDistance=dDistance;
}
public CLPlaceDTO(String sNameOfLocation, LatLng latlng)
{
this.sNameOfLocation = sNameOfLocation;
this.latlng = latlng;
this.dDistance=dDistance;
}}
It's quite possible that the places that you're thinking are closer than the places that are being returned are not true Google places.
Check out this FAQ for getting your business on Google maps: https://support.google.com/places/answer/145585?hl=en .
A test for this could be to attempt to register the business you think is closer with Google places https://www.google.com/local/business/add?hl=en&migratedId=04614545856067425787 and see if it allows you. If you can, this would mean that they are not a true Google place and would not show up in this result set.

RoadManager for osmdroid error

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.

How to use Google maps search functionality api in my application?

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.

Categories

Resources