Click here to Skip to main content
15,891,912 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi, I am trying to show the navigation routes on google map by taking latitude and longitude details of destination location from JSON array and we have already written a code for current location and it is working fine. But problem is with showing a route from current location to destination location. Help me to write a code to show the route in map from current location to destaination location.

What I have tried:

I have already code for JSON which has been taken from assets folder in android studio and the sme is given below:-



package com.example.administrator.jsonnavigation;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class DirectionsJSONParser extends AppCompatActivity {
ArrayList<hospital> list = new ArrayList<>();

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_directions_jsonparser);
}

public void loadJsonFromAssests() {
StringBuffer sb = new StringBuffer();
BufferedReader br = null;
try {
br = new BufferedReader(new InputStreamReader(getAssets().open("jsonData.json")));
String temp;
while ((temp = br.readLine()) != null) {
sb.append(temp);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
String jsonArray = sb.toString();
try {
JSONObject jsonObjMain = new JSONObject(jsonArray);
JSONArray jArray = jsonObjMain.getJSONArray("hospitals");
JSONObject obj;
Hospital details;

for (int i = 0; i < jArray.length(); i++) {
details = new Hospital();
obj = jArray.getJSONObject(i);
details.setName(obj.getString("Name"));
details.setPhoneno(obj.getString("Number"));
details.setLatitude(obj.getDouble("Latitude"));
details.setLongitude(obj.getDouble("Longitude"));
if (obj.getString("Ambulance") == "Y") {
details.setFlag(true);
} else {
details.setFlag(false);
}
list.add(details);

}
} catch (JSONException e) {
e.printStackTrace();
}
}

public List<list><hashmap><string,string>>> parse(JSONObject jObject) {
loadJsonFromAssests();
//return null; }
}

MapAcitvity:-
package com.example.administrator.jsonnavigation;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;

import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class MapsActivity extends FragmentActivity {

GoogleMap map;
ArrayList<latlng> markerPoints;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);

// Initializing
markerPoints = new ArrayList<latlng>();

// Getting reference to SupportMapFragment of the activity_main
SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);

// Getting Map for the SupportMapFragment
map = fm.getMap();

if (map != null) {

// Enable MyLocation Button in the Map
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
map.setMyLocationEnabled(true);

// Setting onclick event listener for the map
map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {

@Override
public void onMapClick(LatLng point) {

// Already two locations
if(markerPoints.size()>1){
markerPoints.clear();
map.clear();
}

// Adding new item to the ArrayList
markerPoints.add(point);

// Creating MarkerOptions
MarkerOptions options = new MarkerOptions();

// Setting the position of the marker
options.position(point);

/**
* For the start location, the color of marker is GREEN and
* for the end location, the color of marker is RED.
*/
if(markerPoints.size()==1){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_GREEN));
}else if(markerPoints.size()==2){
options.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED));
}

// Add new marker to the Google Map Android API V2
map.addMarker(options);

// Checks, whether start and end locations are captured
if(markerPoints.size() >= 2){
LatLng origin = markerPoints.get(0);
LatLng dest = markerPoints.get(1);

// Getting URL to the Google Directions API
String url = getDirectionsUrl(origin, dest);

DownloadTask downloadTask = new DownloadTask();

// Start downloading json data from Google Directions API
downloadTask.execute(url);
}
}
});
}
}

private String getDirectionsUrl(LatLng origin,LatLng dest){

// Origin of route
String str_origin = "origin="+origin.latitude+","+origin.longitude;

// Destination of route
String str_dest = "destination="+dest.latitude+","+dest.longitude;

// Sensor enabled
String sensor = "sensor=false";

// Building the parameters to the web service
String parameters = str_origin+"&"+str_dest+"&"+sensor;

// Output format
String output = "json";

// Building the url to the web service
String url = "https://maps.googleapis.com/maps/api/directions/"+output+"?"+parameters;

return url;
}
/** A method to download json data from url */
private String downloadUrl(String strUrl) throws IOException {
String data = "";
InputStream iStream = null;
HttpURLConnection urlConnection = null;
try{
URL url = new URL(strUrl);

// Creating an http connection to communicate with url
urlConnection = (HttpURLConnection) url.openConnection();

// Connecting to url
urlConnection.connect();

// Reading data from url
iStream = urlConnection.getInputStream();

BufferedReader br = new BufferedReader(new InputStreamReader(iStream));

StringBuffer sb = new StringBuffer();

String line = "";
while( ( line = br.readLine()) != null){
sb.append(line);
}

data = sb.toString();

br.close();

}catch(Exception e){
Log.d("Exception while downloading url", e.toString());
}finally{
iStream.close();
urlConnection.disconnect();
}
return data;
}

// Fetches data from url passed
private class DownloadTask extends AsyncTask<string,> {

// Downloading data in non-ui thread
@Override
protected String doInBackground(String... url) {

// For storing data from web service
String data = "";

try{
// Fetching the data from web service
data = downloadUrl(url[0]);
}catch(Exception e){
Log.d("Background Task",e.toString());
}
return data;
}

// Executes in UI thread, after the execution of
// doInBackground()
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);

ParserTask parserTask = new ParserTask();

// Invokes the thread for parsing the JSON data
parserTask.execute(result);
}
}

/** A class to parse the Google Places in JSON format */
private class ParserTask extends AsyncTask<string,>>> >{

// Parsing the data in non-ui thread
@Override
protected List<list><hashmap><string,>>> doInBackground(String... jsonData) {

JSONObject jObject;
List<list><hashmap><string,>>> hospitals = null;

try{
jObject = new JSONObject(jsonData[0]);
DirectionsJSONParser parser = new DirectionsJSONParser();

// Starts parsing data

hospitals = parser.parse(jObject);
}catch(Exception e){
e.printStackTrace();
}
return hospitals;
}

// Executes in UI thread, after the parsing process
@Override
protected void onPostExecute(List<list><hashmap><string,>>> result) {
ArrayList<latlng> points = null;
PolylineOptions lineOptions = null;
MarkerOptions markerOptions = new MarkerOptions();

// Traversing through all the routes
for(int i=0;i<result.size();i++){>
points = new ArrayList<latlng>();
lineOptions = new PolylineOptions();

// Fetching i-th route
List<hashmap><string,>> path = result.get(i);

// Fetching all the points in i-th route
for(int j=0;j<path.size();j++){>
HashMap<string,string> point = path.get(j);

double lat = Double.parseDouble(point.get("latitude"));
double lng = Double.parseDouble(point.get("longitude"));
LatLng position = new LatLng(lat, lng);

points.add(position);
}

// Adding all the points in the route to LineOptions
lineOptions.addAll(points);
lineOptions.width(2);
lineOptions.color(Color.RED);
}

// Drawing polyline in the Google Map for the i-th route
map.addPolyline(lineOptions);
}
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
Hospitl class:-
package com.example.administrator.jsonnavigation;

/**
* Created by Administrator on 4/29/2016.
*/
public class Hospital {
String name, address, phoneno;
int image;
double latitude, longitude;
Boolean flag;

public Boolean getFlag() {
return flag;
}

public void setFlag(Boolean flag) {
this.flag = flag;
}

public double getLatitude() {
return latitude;
}

public void setLatitude(double latitude) {
this.latitude = latitude;
}

public double getLongitude() {
return longitude;
}

public void setLongitude(double longitude) {
this.longitude = longitude;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getAddress() {
return address;
}

public void setAddress(String address) {
this.address = address;
}

public String getPhoneno() {
return phoneno;
}

public void setPhoneno(String phoneno) {
this.phoneno = phoneno;
}

public int getImage() {
return image;
}

public void setImage(int image) {
this.image = image;
}
}



Activity_maps.xml:-
<fragment xmlns:android="http://schemas.android.com/apk/res/android">
xmlns:map="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/map"
android:name="com.google.android.gms.maps.SupportMapFragment"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.administrator.jsonnavigation.MapsActivity" />
Manifest file:-

<manifest xmlns:android="http://schemas.android.com/apk/res/android">
package="com.example.administrator.jsonnavigation">

<!--
The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
Google Maps Android API v2, but you must specify either coarse or fine
location permissions for the 'MyLocation' functionality.
-->
<uses-sdk>
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.INTERNET">

<permission>
android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE"
android:protectionLevel="signature" />

<uses-permission android:name="in.wptrafficanalyzer.locationroutedirectionmapv2.permission.MAPS_RECEIVE">

<uses-permission android:name="android.permission.INTERNET">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE">
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES">
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
<uses-feature>
android:glEsVersion="0x00020000"
android:required="true"/>
<application>
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">

<!--
The API key for Google Maps-based APIs is defined as a string resource.
(See the file "res/values/google_maps_api.xml").
Note that the API key is linked to the encryption key used to sign the APK.
You need a different API key for each encryption key, including the release key that is used to
sign the APK for publishing.
You can define the keys for the debug and release targets in src/debug/ and src/release/.
-->
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="@string/google_maps_key" />

<activity>
android:name=".MapsActivity"
android:label="@string/title_activity_maps">
<intent-filter>
<action android:name="android.intent.action.MAIN">

<category android:name="android.intent.category.LAUNCHER">


<activity android:name=".DirectionsJSONParser">



But the above code is not working and I am unable to parse the longitude and latitude details of destination location which is available in JSON array please help regarding this
Posted

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900