Map latitude and longitude is showing in sea in android? - android

From a json feed am getting all the latitude and longitude and adding all in mapview. Am gettin different markers.but all the points are showing in sea. this is my code. can anyone help me please
MapItemizedOverlay itemizedoverlay;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
url = "http://dentonsweb.com/app/html/android/get.php?what=Hotels&lat=51.507222&lon=-0.1275&pg=0";
System.out.println("url is "+url);
Jsonfunctions jParser = new Jsonfunctions();
JSONObject json = jParser.getJSONFromUrl(url);
try {
// Getting Array of Contacts
results = json.getJSONArray(TAG_RESULTS);
// looping through All Contacts
for (int i = 0; i < results.length(); i++) {
JSONObject c = results.getJSONObject(i);
id = c.getString(TAG_ID);
name = c.getString(TAG_NAME);
System.out.println("name is " + name);
adress = c.getString(TAG_ADRRESS);
latitude = c.getString(TAG_LATITUDE);
latitudeAry.add(c.getString(TAG_LATITUDE).toString());
longitude = c.getString(TAG_lONGITUDE);
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
distance = c.getString(TAG_DISTANCE);
image = c.getString(TAG_IMAGE);
phone = c.getString(TAG_TELEPHONE);
telphonenumberAry
.add(c.getString(TAG_TELEPHONE).toString());
NameAry.add(c.getString(TAG_NAME).toString());
resourceAry.add(new ResourceClass(point,id, name, adress,image,
distance, latitude, longitude, phone));
System.out.println("arraooosdospodpsodps " + resourceAry);
}
} catch (JSONException e) {
e.printStackTrace();
}
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
mc = mapView.getController();
listOfOverlays = mapView.getOverlays();
drawable = this.getResources().getDrawable(
R.drawable.pin);
itemizedoverlay = new MapItemizedOverlay(drawable,mapView);
for (int i = 0; i < resourceAry.size(); i++) {
// latitude = resourceAry.get(i).getLatitude();
System.out.println("latitude is " + latitude);
String latitude = resourceAry.get(i).getLatitude();
String longitude = resourceAry.get(i).getLongitude();
// longitude = resourceAry.get(i).getLongitude();
String name = resourceAry.get(i).getName();
System.out.println("Name is" + name);
String adress = resourceAry.get(i).getAdress();
if (!latitude.equals("") && !longitude.equals("")) {
Double latitude_next = Double.parseDouble(latitude);
Double longitude_next = Double.parseDouble(longitude);
point = new GeoPoint((int) (latitude_next * 1E6),
(int) (longitude_next * 1E6));
System.out.println("point is " + point);
overlayitem = new OverlayItem(point,resourceAry.get(i).getName(),resourceAry.get(i).getAdress());
// System.out.println( " spanned text: " +
// Html.fromHtml(Texte));
itemizedoverlay.addOverlay(overlayitem);
listOfOverlays.add(itemizedoverlay);
}
}
mc.animateTo(point);
mc.setZoom(13);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}

#harish --
You get latitude & longitudes like 51.509998321533,-0.12999999523163
but in android geopoint accepts only int values.
now create a function which will take these values & restric them upto 6 decimal points & you will get result as you wanted
Function will be like
double roundTwoDecimals(double d){
DecimalFormat twoDForm = new DecimalFormat("#.######");
return Double.valueOf(twoDForm.format(d));
}
this way you will get double value & then multiply it with 10E6 & you will get int which you need to use in creating GeoPoints..

I am not suere if it makes a difference but the line
latitudeAry.add(c.getString(TAG_lONGITUDE).toString());
has a lowercase L in lONGITUDE

Related

How to remove the extra polyline from google maps api android

I have added a waypoint and drawn the polyline from start to destination through the waypoint. But an extra straight line is drawn from start to destination. How can I remove it ?
The code below shows the ParserTask and getDirections URL.
private class ParserTask extends AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
// Parsing the data in non-ui thread
#Override
protected List<List<HashMap<String, String>>> doInBackground(String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();
routes = parser.parse(jObject);
Log.d("routes", routes.toString());
Log.d("jObject", jObject.toString());
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = new ArrayList<LatLng>();;
PolylineOptions lineOptions = new PolylineOptions();;
lineOptions.width(2);
lineOptions.color(Color.RED);
MarkerOptions markerOptions = new MarkerOptions();
// Traversing through all the routes
for(int i=0;i<result.size();i++){
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
lineOptions.geodesic(true);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
private String getDirectionsUrl(LatLng origin_start, LatLng dest, LatLng waypoint_xx) {
String origin = "origin=" + origin_start.latitude + "," + origin_start.longitude;
//String waypointss = "waypoints=optimize:true|" + waypoint_xx.latitude + "," + waypoint_xx.longitude ;
String destination = "destination=" + dest.latitude + "," + dest.longitude;
// Waypoints
String waypoints = "";
for(int i=2;i<markerPoints.size();i++){
LatLng point = (LatLng) markerPoints.get(i);
if(i==2)
waypoints = "waypoints=";
waypoints += point.latitude + "," + point.longitude + "|";
}
String sensor = "sensor=false";
String alternative = "alternatives=false";
String params = origin + "&" + destination + "&" + alternative + "&" + sensor + "&" + waypoints ;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}
This code is the Directions JSON Parser
public class DirectionsJSONParser {
/** Receives a JSONObject and returns a list of lists containing latitude and longitude */
public List<List<HashMap<String,String>>> parse(JSONObject jObject){
List<List<HashMap<String, String>>> routes = new ArrayList<List<HashMap<String,String>>>() ;
JSONArray jRoutes = null;
JSONArray jLegs = null;
JSONArray jSteps = null;
try {
jRoutes = jObject.getJSONArray("routes");
/** Traversing all routes */
for(int i=0;i<jRoutes.length();i++){
jLegs = ( (JSONObject)jRoutes.get(i)).getJSONArray("legs");
List path = new ArrayList<HashMap<String, String>>();
/** Traversing all legs */
for(int j=0;j<jLegs.length();j++){
jSteps = ( (JSONObject)jLegs.get(j)).getJSONArray("steps");
/** Traversing all steps */
for(int k=0;k<jSteps.length();k++){
String polyline = "";
polyline = (String)((JSONObject)((JSONObject)jSteps.get(k)).get("polyline")).get("points");
List list = decodePoly(polyline);
/** Traversing all points */
for(int l=0;l <list.size();l++){
HashMap<String, String> hm = new HashMap<String, String>();
hm.put("lat", Double.toString(((LatLng)list.get(l)).latitude) );
hm.put("lng", Double.toString(((LatLng)list.get(l)).longitude) );
path.add(hm);
}
}
routes.add(path);
}
}
} catch (JSONException e) {
e.printStackTrace();
}catch (Exception e){
}
return routes;
}
/**
* Method to decode polyline points
* Courtesy : http://jeffreysambells.com/2010/05/27/decoding-polylines-from-google-maps-direction-api-with-java
* */
private List decodePoly(String encoded) {
List poly = new ArrayList();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
LatLng p = new LatLng((((double) lat / 1E5)),
(((double) lng / 1E5)));
poly.add(p);
}
return poly;
}
}
This is the Download Task
private class DownloadTask extends AsyncTask<String, Void, String> {
#Override
protected String doInBackground(String... url) {
String data = "";
try {
data = downloadUrl(url[0]);
} catch (Exception e) {
Log.d("Background Task", e.toString());
}
Log.d("parserTask data", data.toString());
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ParserTask parserTask = new ParserTask();
Log.d("parserTask result", result.toString());
parserTask.execute(result);
}
}
And finally the onMapReady method
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
UiSettings uiSettings = googleMap.getUiSettings();
//uiSettings.setCompassEnabled(false);
uiSettings.setZoomControlsEnabled(true);
//-------------
// mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
//Initialize Google Play Services
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
buildGoogleApiClient();
mMap.setMyLocationEnabled(true);
}
//-------------
DatabaseReference myRef = FirebaseDatabase.getInstance().getReference().child("location");
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(MapsActivity.this)
.setSmallIcon(R.drawable.applogo)
.setContentTitle("Trip Request")
.setContentText("Click to accept trip!");
manager = (NotificationManager) MapsActivity.this.getSystemService( MapsActivity.this.NOTIFICATION_SERVICE );
manager.notify(0, builder.build());
// sendNotification();
startLatFB = (Double) dataSnapshot.child("startLat").getValue();
startLonFB = (Double) dataSnapshot.child("startLon").getValue();
endLatFB = (Double) dataSnapshot.child("endLat").getValue();
endLonFB = (Double) dataSnapshot.child("endLon").getValue();
Log.d("startLat", startLatFB.toString());
Log.d("startLon", startLonFB.toString());
Log.d("endLat", endLatFB.toString());
Log.d("endLon", endLonFB.toString());
if (markerPoints.size() > 1) {
markerPoints.clear();
mMap.clear();
}
double startLat = startLatFB; //SLIIT
double startLon = startLonFB;
double wayPointLat = 6.9040322; //FAB - Malabe
double wayPointLon = 79.948803;
double wayPointLatTwo = 6.053519; //FAB - Malabe
double wayPointLonTwo = 80.220977;
double endLat = endLatFB; //MAS
double endLon = endLonFB;
LatLng start_latLng = new LatLng(startLat, startLon);
LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
LatLng end_latLng = new LatLng(endLat, endLon);
// LatLng start_latLng = new LatLng(startLatFB, startLonFB);
// LatLng waypoint_latLng = new LatLng(wayPointLat, wayPointLon);
// LatLng end_latLng = new LatLng(endLatFB, endLonFB);
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(start_latLng, 11));
mMap.animateCamera(CameraUpdateFactory.newLatLngZoom(start_latLng,11f));
// start_latLng = startLatFB;
// Adding new item to the ArrayList
markerPoints.add(start_latLng);
markerPoints.add(end_latLng);
markerPoints.add(waypoint_latLng);
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
MarkerOptions optionsTwo = new MarkerOptions();
MarkerOptions optionsThree = new MarkerOptions();
BitmapDescriptor icon = BitmapDescriptorFactory.fromResource(R.drawable.startlocation);
BitmapDescriptor icon2 = BitmapDescriptorFactory.fromResource(R.drawable.endlocation);
// Setting the position of the marker
options.position(start_latLng);
optionsTwo.position(end_latLng);
optionsThree.position(waypoint_latLng);
if (markerPoints.size() == 1) {
options.icon(icon);
} else if (markerPoints.size() == 2) {
options.icon(icon2);
}
// Add new marker to the Google Map Android API V2
mMap.addMarker(options);
mMap.addMarker(optionsTwo);
mMap.addMarker(optionsThree);
// Checks, whether start and end locations are captured
if (markerPoints.size() >= 3) {
LatLng origin = (LatLng) markerPoints.get(0);
LatLng dest = (LatLng) markerPoints.get(1);
LatLng waypointss = (LatLng) markerPoints.get(2);
Log.d("origin url", origin.toString());
Log.d("dest url", origin.toString());
Log.d("waypoint url", origin.toString());
// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest, waypointss);
DownloadTask downloadTask = new DownloadTask();
// Start downloading json data from Google Directions API
downloadTask.execute(url);
Log.d("DownloadTask url", url);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
Try initializing new Arraylist of Points each time while traversing.
Here is a sample:
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> result) {
ArrayList<LatLng> points = null;
PolylineOptions lineOptions = null;
// Traversing through all the routes
for(int i=0;i<result.size();i++){
points = new ArrayList<LatLng>(); //initialize here
lineOptions = new PolylineOptions();
// Fetching i-th route
List<HashMap<String, String>> path = result.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
lineOptions.addAll(points);
lineOptions.width(12);
lineOptions.color(Color.RED);
}
// Drawing polyline in the Google Map for the i-th route
mMap.addPolyline(lineOptions);
}
}
For detail implementation Go through This Link

Android Google Maps v2 Routes display routes not working

I'm trying to set routes directions in my app using google API v2 but I'm getting this error that I can't find what is causing the problem
D/Exception while reading url﹕ java.io.FileNotFoundException: https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false
And when I copy and paste that link on Chrome I get the following:
"error_message" : "Invalid request. Missing the 'origin' parameter.",
This is my map Class:
public class MapaViagem extends FragmentActivity {
private GoogleMap googleMap;
private String IdViagem;
private List<EnderecoModel> mEnderecoModel = new ArrayList<EnderecoModel>();
private ArrayList<LatLng> coordList = new ArrayList<LatLng>();
private ProgressDialog dialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);
setContentView(R.layout.maps);
// Loading map
initilizeMap();
// Changing map type
googleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
// googleMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
// googleMap.setMapType(GoogleMap.MAP_TYPE_SATELLITE);
// googleMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
// googleMap.setMapType(GoogleMap.MAP_TYPE_NONE);
// Showing / hiding your current location
googleMap.setMyLocationEnabled(true);
// Enable / Disable zooming controls
googleMap.getUiSettings().setZoomControlsEnabled(true);
// Enable / Disable my location button
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
// Enable / Disable Compass icon
googleMap.getUiSettings().setCompassEnabled(true);
// Enable / Disable Rotate gesture
googleMap.getUiSettings().setRotateGesturesEnabled(true);
// Enable / Disable zooming functionality
googleMap.getUiSettings().setZoomGesturesEnabled(true);
try {
Bundle parametros = getIntent().getExtras();
IdViagem = parametros.getString("id_viagem");
Repositorio mRepositorio = new Repositorio(this);
String waypoints = "waypoints=optimize:true";
String coordenadas = "";
mEnderecoModel = mRepositorio.getListaEnderecosDaViagem(Integer.valueOf(IdViagem));
for (int j = 0; j < mEnderecoModel.size(); j++) {
float latitude = Float.parseFloat(mEnderecoModel.get(j).getLatitude());
float longitude = Float.parseFloat(mEnderecoModel.get(j).getLongitude());
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(latitude, longitude), 10));
coordenadas += "|" + latitude + "," + longitude;
coordList.add(new LatLng(latitude, longitude));
// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();
// Setting the position of the marker
options.position(new LatLng(latitude, longitude));
if (j == mEnderecoModel.size() - 1) {
options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.vermelho, String.valueOf(mEnderecoModel.size()))));
} else {
options.icon(BitmapDescriptorFactory.fromBitmap(writeTextOnDrawable(R.drawable.verde, String.valueOf(j + 1))));
}
// Add new marker to the Google Map Android API V2
googleMap.addMarker(options);
}
String sensor = "sensor=false";
String params = waypoints + coordenadas + "&" + sensor;
String url = "https://maps.googleapis.com/maps/api/directions/json?" + params;
ReadTask downloadTask = new ReadTask();
downloadTask.execute(url);
} catch (Exception e) {
e.printStackTrace();
}
}
private class ReadTask extends AsyncTask<String, String, String> {
#Override
protected void onPreExecute() {
dialog = new ProgressDialog(MapaViagem.this);
// setup your dialog here
dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
dialog.setTitle("Traçando Rotas");
dialog.setMessage("Aguarde...");
dialog.setCancelable(false);
dialog.show();
}
#Override
protected String doInBackground(String... url) {
String data = "";
try {
HttpConnection http = new HttpConnection();
data = http.readUrl(url[0]);
} catch (Exception e) {
e.printStackTrace();
}
return data;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
new ParserTask().execute(result);
}
}
private class ParserTask extends
AsyncTask<String, Integer, List<List<HashMap<String, String>>>> {
#Override
protected List<List<HashMap<String, String>>> doInBackground(
String... jsonData) {
JSONObject jObject;
List<List<HashMap<String, String>>> routes = null;
try {
jObject = new JSONObject(jsonData[0]);
PathJSONParser parser = new PathJSONParser();
routes = parser.parse(jObject);
} catch (Exception e) {
e.printStackTrace();
}
return routes;
}
#Override
protected void onPostExecute(List<List<HashMap<String, String>>> routes) {
ArrayList<LatLng> points = null;
PolylineOptions polyLineOptions = null;
if(routes != null){
for (int i = 0; i < routes.size(); i++) {
points = new ArrayList<LatLng>();
polyLineOptions = new PolylineOptions();
List<HashMap<String, String>> path = routes.get(i);
for (int j = 0; j < path.size(); j++) {
HashMap<String, String> point = path.get(j);
double lat = Double.parseDouble(point.get("lat"));
double lng = Double.parseDouble(point.get("lng"));
LatLng position = new LatLng(lat, lng);
points.add(position);
}
polyLineOptions.addAll(points);
polyLineOptions.width(4);
polyLineOptions.color(Color.BLUE);
}
googleMap.addPolyline(polyLineOptions);
}
if (dialog.isShowing()) {
dialog.dismiss();
}
}
}
private Bitmap writeTextOnDrawable(int drawableId, String text) {
Bitmap bm = BitmapFactory.decodeResource(getResources(), drawableId)
.copy(Bitmap.Config.ARGB_8888, true);
Typeface tf = Typeface.create("Helvetica", Typeface.BOLD);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTypeface(tf);
paint.setTextAlign(Paint.Align.CENTER);
paint.setTextSize(convertToPixels(MapaViagem.this, 11));
Rect textRect = new Rect();
paint.getTextBounds(text, 0, text.length(), textRect);
Canvas canvas = new Canvas(bm);
//If the text is bigger than the canvas , reduce the font size
if (textRect.width() >= (canvas.getWidth() - 4)) //the padding on either sides is considered as 4, so as to appropriately fit in the text
paint.setTextSize(convertToPixels(MapaViagem.this, 7)); //Scaling needs to be used for different dpi's
//Calculate the positions
int xPos = (canvas.getWidth() / 2) - 1; //-2 is for regulating the x position offset
//"- ((paint.descent() + paint.ascent()) / 2)" is the distance from the baseline to the center.
int yPos = (int) ((canvas.getHeight() / 2) - ((paint.descent() + paint.ascent()) / 8f));
canvas.drawText(text, xPos, yPos, paint);
return bm;
}
public static int convertToPixels(Context context, int nDP) {
final float conversionScale = context.getResources().getDisplayMetrics().density;
return (int) ((nDP * conversionScale) + 0.5f);
}
private void initilizeMap() {
if (googleMap == null) {
googleMap = ((MapFragment) getFragmentManager().findFragmentById(
R.id.map)).getMap();
// check if map is created successfully or not
if (googleMap == null) {
Toast.makeText(getApplicationContext(),
"Não foi possível carregar o mapa", Toast.LENGTH_SHORT)
.show();
}
}
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
#Override
public void onBackPressed() {
super.onBackPressed();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_mapa, menu);
return super.onCreateOptionsMenu(menu);
}
#TargetApi(Build.VERSION_CODES.HONEYCOMB)
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
super.onBackPressed();
overridePendingTransition(R.anim.animation_back, R.anim.animation_back_leave);
finish();
return true;
case R.id.menu_atualizar_mapa:
/* dispara os repositorios a sincronizar */
new Sincronizar(MapaViagem.this, MapaViagem.this).execute(0);
}
return true;
}
#Override
protected void onResume() {
super.onResume();
initilizeMap();
}
}
The url which is being generated in the code : "https://maps.googleapis.com/maps/api/directions/json?waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false"
is WRONG.
Your URL should be like this : "https://maps.googleapis.com/maps/api/directions/json?origin=-23.3246,-51.1489&destination=-23.2975,-51.2007&%20waypoints=optimize:true|-23.3246,-51.1489|-23.3206,-51.1459|-23.2975,-51.2007&sensor=false"
Here's the code to generate the url :
private String getMapsApiDirectionsUrl(LatLng Office, LatLng home) {
String waypoints = "waypoints=optimize:true|"
+ Office.latitude + "," + Office.longitude
+ "|" + "|" + home.latitude + ","
+ home.longitude;
String OriDest = "origin="+Office.latitude+","+Office.longitude+"&destination="+home.latitude+","+home.longitude;
String sensor = "sensor=false";
String params = OriDest+"&%20"+waypoints + "&" + sensor;
String output = "json";
String url = "https://maps.googleapis.com/maps/api/directions/"
+ output + "?" + params;
return url;
}

Ho do i use google places to find a place in android

Just now I've purchased Google API Key. I've find the exact place by using google Places. The most important thing is I've to find the place programmatically which means that When I open my application it will display the place in a textview. Also i want to find the nearest places.
Can anyone please explain with a complete sample code (in java, not java script code)
You can use following code for Google places Api
Here i have search airports but you can search your own places and when you find
here getJsonResponse id your httpclient
String url = "https://maps.googleapis.com/maps/api/place/textsearch/json?query="**Place To Search**"&sensor=true&key=**Your Api Key**";
String res = getJsonRespose(url);
if (res != null && !res.equalsIgnoreCase("")) {
JSONObject jObject = new JSONObject(res);
// if (jObject.getString("status").equalsIgnoreCase("ok")) {
JSONArray jArray = jObject.getJSONArray("results");
if (jArray.length() > 0) {
for (int i = 0; i < jArray.length(); i++) {
AirportListData adata = new AirportListData();
JSONObject geo = jArray.getJSONObject(i);
JSONObject jLocation = geo.getJSONObject("geometry");
JSONObject jgetLocation = jLocation
.getJSONObject("location");
Address = geo.getString("formatted_address");
name = geo.getString("name");
adata.setAirportName(name);
lat = jgetLocation.getDouble("lat");
lng = jgetLocation.getDouble("lng");
adata.setLat(lat);
adata.setLng(lng);
double dis = getDistance(lat, lng);
adata.setAddress(Address);
adata.setDistnace(dis / 1000);
ardata.add(adata);
Log.e("address", "Distance" + (dis / 1000) + "Address"
+ Address + "name" + name + "lat" + lat + "lng"
+ lng);
}
}
}
When You got All places you can Call getDistance Method and find distance between your current place and places you got and after calculating that you got nearest place
public static double getDistance(double lat, double lng) {
try {
float[] result = new float[3];
// Log.e("lat long : ", c.getDouble(1) + " : " + c.getDouble(2) +
// " : " + latitude + " : " + longitude);
Location.distanceBetween(Constantdata.lat, Constantdata.lon, lat,
lng, result);
double distance = ((double) result[0]);
return distance;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return 0.0;
}
Here Constantdata.lat and constant.lon is your current latitude and longitude and lat long is places latitude and logitude that you got

How to put JSON lattitude and longitude on the map [duplicate]

This question already has an answer here:
Closed 10 years ago.
Possible Duplicate:
How to put JSON lOutput (latitude and longitude) on the map
I have a main activity which parses the JSON data from my mysql (table tracking:Lattitude and longitude) Now I want to pass this data in to my MapActivity and display on google maps. Any help is highly appreciated. Thanks!
this my JSONactivity
public class JSONActivity extends Activity{
private JSONObject jObject;
private String xResult ="";
//Seusuaikan url dengan nama domain
private String url = "http://10.0.2.2/labiltrack/daftartracking.php";
#Override
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.daftartrack);
TextView txtResult = (TextView)findViewById(R.id.TextViewResult);
//url += "?lattitude=" + UserData.getEmail();
xResult = getRequest(url);
try {
parse(txtResult);
} catch (Exception e) {
e.printStackTrace();
}
}
private void parse(TextView txtResult) throws Exception {
// TODO Auto-generated method stub
jObject = new JSONObject(xResult);
JSONArray menuitemArray = jObject.getJSONArray("joel");
String sret="";
//int j = 0;
for (int i = 0; i < menuitemArray.length(); i++) {
sret +=menuitemArray.getJSONObject(i).
getString("lattitude").toString()+" : ";
System.out.println(menuitemArray.getJSONObject(i)
.getString("lattitude").toString());
System.out.println(menuitemArray.getJSONObject(i).getString(
"longitude").toString());
sret +=menuitemArray.getJSONObject(i).getString(
"lattitude").toString()+"\n";
//j=i;
}txtResult.setText(sret);
}
/**
* Method untuk Mengirimkan data keserver
* event by button login diklik
*
* #param view
*/
private String getRequest(String url) {
// TODO Auto-generated method stub
String sret="";
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try{
HttpResponse response = client.execute(request);
sret =request(response);
}catch(Exception ex){
Toast.makeText(this,"jo "+sret, Toast.LENGTH_SHORT).show();
}
return sret;
}
/**
* Method untuk Menenrima data dari server
* #param response
* #return
*/
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try{
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
str.append(line + "\n");
}
in.close();
result = str.toString();
}catch(Exception ex){
result = "Error";
}
return result;
}
}
and this my mapActivity
public class mapactivity extends MapActivity {
private MapView mapView;
MapController mc;
GeoPoint p;
//private MyLocationOverlay me = null;
class MapOverlays extends com.google.android.maps.Overlay
{
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//translate the geopoint to screen pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//tambah marker
Bitmap bmp = BitmapFactory.decodeResource(getResources (), R.drawable.pin_red);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
//mapView.setSatellite(true);
return true;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1) {
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
mc.animateTo(p);
//geocoding
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
p.getLatitudeE6() / 1E6,
p.getLongitudeE6() / 1E6, 1);
String add = "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();
i++)
add += addresses.get(0).getAddressLine(i) + "\n";
}
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT).show();
}
catch (IOException e) {
e.printStackTrace();
}
return true;
}
else
return false;
} }
/** Called when the activity is first created. */
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mapview1);
//utk mnampilkan zoom
mapView = (MapView) findViewById(R.id.mapView);
LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);
View zoomView = mapView.getZoomControls();
zoomLayout.addView(zoomView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT,
LayoutParams.FILL_PARENT));
mapView.displayZoomControls(true);
//menampilkan default peta banda aceh
mc = mapView.getController();
String coordinates[] = {"5.550381", "95.318699"};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(14);
mapView.invalidate();
//tambah marker
MapOverlays mapOverlay = new MapOverlays();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
public void btnSatelitClick(View v){
mapView.setSatellite(true);
mapView.setStreetView(false);
}
public void btnjalanClick (View v){
mapView.setSatellite(false);
mapView.setStreetView(true);
}
protected boolean isRouteDisplayed()
{
//auto generate method
return false;
}
}
as you have only to variable to pass so use intent and pass the data ......and i think you have rest of code writen
put in the JSONActivity from where you want to open mapActivity and you alos have the variable latitude and longitude with their values
Intent i= new Intent(getApplicationContext(), mapActivity.class);
i.putExtra("lattitude",lattitude);
i.putExtra("longitude",longitude);
startActivity(i);
Then in the new activity mapActivity, retrieve those values:
inplace of this put String coordinates[] = {"5.550381", "95.318699"};
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String lattitude= extras.getString("lattitude");
String longitude= extras.getString("longitude");
double lat = Double.parseDouble(lattitude);
double lng = Double.parseDouble(longitude);
}

How to get Latitude/Longitude from JSON responsed by google map apis

I am not able to properly extract out the latitude and longitude point set to draw route further. Can anybody get me the code to do so?
Thanks in advance
public class MapprojectActivity extends MapActivity {
/** Called when the activity is first created. */
static final String TAG_RESULTS = "results";
static final String TAG_GEO = "geometry";
static final String TAG_LOCATION = "location";
static final String TAG_LAT = "lat";
static final String TAG_LNG = "lng";
JSONArray res = null;
MapView mapView;
List<Overlay> mapOverlays;
Drawable drawable;
MyItemizedOverlay itemizedOverlay;
static String url = "http://maps.google.com/maps/api/geocode/json?address=guindy,+chennai,+IN&sensor=false";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map);
TextView lattv=(TextView)findViewById(R.id.lat);
TextView lngtv=(TextView)findViewById(R.id.lng);
JSONParstring jParser = new JSONParstring();
// getting JSON string from URL
try
{
JSONObject jobj = new JSONObject(json);
res = jobj.getJSONArray(TAG_RESULTS);
for(int i = 0; i < res.length(); i++){
JSONObject c = res.getJSONObject(i);
JSONObject loc = c.optJSONObject(TAG_GEO).optJSONObject(TAG_LOCATION);
String lat =loc.getString(TAG_LAT);
String lng = loc.getString(TAG_LNG);
lattv.setText(lat);
lngtv.setText(lng);
}
}
catch (JSONException e){ }
String i=(String) lattv.getText();
String j=(String) lngtv.getText();
double lat1 = Double.parseDouble(i);
double lng1 = Double.parseDouble(j);
mapView = (MapView) findViewById(R.id.map_view);
mapView.setBuiltInZoomControls(false);
mapOverlays = mapView.getOverlays();
drawable = getResources().getDrawable(R.drawable.mark1);
itemizedOverlay = new MyItemizedOverlay(drawable, mapView);
GeoPoint point = new GeoPoint((int)(lat1*1E6),(int)(lng1*1E6));
OverlayItem overlayItem = new OverlayItem(point, "Amy Jones",
"(checked in Lemon-tree with friends lisa wong, paul jones)");
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
final MapController mc = mapView.getController();
mc.animateTo(point);
mc.setZoom(16);
// Integer i = Integer.valueOf((String) lattv.getText());
// Integer j = Integer.valueOf((String) lngtv.getText());
// // first overlay
}
protected boolean isRouteDisplayed() {
return false;
}
}
Here is to get Latitude/Longitude from JSON http://blog.synyx.de/2010/06/routing-driving-directions-on-android-part-1-get-the-route/
And this is how to draw a route http://blog.synyx.de/2010/06/routing-driving-directions-on-android-%E2%80%93-part-2-draw-the-route/
u should study it. i hope it'll help.

Categories

Resources