I was playing around with the Google Maps API V2 on android.
Trying to get a path between 2 locations and doing this with the JSON Parsing.
I am getting a route. and the route starts out how it should be. but then at one point it goes the wrong way.
My end destination ends up wrong. And with some other locations my app just gets terminated.
This is what i have done
Here is my makeURL method
public String makeUrl(){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin="); //start positie
urlString.append(Double.toString(source.latitude));
urlString.append(",");
urlString.append(Double.toString(source.longitude));
urlString.append("&destination="); //eind positie
urlString.append(Double.toString(dest.latitude));
urlString.append(",");
urlString.append(Double.toString(dest.longitude));
urlString.append("&sensor=false&mode=driving");
return urlString.toString();
}
my JSON parser
public class JSONParser {
static InputStream is = null;
static JSONObject jObj = null;
static String json = "";
public JSONParser() {
// TODO Auto-generated constructor stub
}
public String getJSONFromURL(String url){
try {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch(UnsupportedEncodingException e){
e.printStackTrace();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while((line = reader.readLine()) != null){
sb.append(line + "\n");
//Log.e("test: ", sb.toString());
}
json = sb.toString();
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
Log.e("buffer error", "Error converting result " + e.toString());
}
return json;
}
I draw my Path with this method
public void drawPath(String result){
try{
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
Log.d("test: ", encodedString);
List<LatLng> list = decodePoly(encodedString);
LatLng last = null;
for (int i = 0; i < list.size()-1; i++) {
LatLng src = list.get(i);
LatLng dest = list.get(i+1);
last = dest;
Log.d("Last latLng:", last.latitude + ", " + last.longitude );
Polyline line = googleMap.addPolyline(new PolylineOptions().add(
new LatLng(src.latitude, src.longitude), new LatLng(dest.latitude, dest.longitude))
.width(2)
.color(Color.BLUE));
}
Log.d("Last latLng:", last.latitude + ", " + last.longitude );
}catch (JSONException e){
e.printStackTrace();
}
}
And I decode my JSON with
private List<LatLng> decodePoly(String encoded){
List<LatLng> poly = new ArrayList<LatLng>();
int index = 0;
int length = encoded.length();
int latitude = 0;
int longitude = 0;
while(index < length){
int b;
int shift = 0;
int result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int destLat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
latitude += destLat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b > 0x20);
int destLong = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
longitude += destLong;
poly.add(new LatLng((latitude / 1E5),(longitude / 1E5) ));
}
return poly;
}
And then coded with an AsyncTask
Thanks in advance.
Sorry for the long wait.. i have fixed it a while ago but i hadn't put my solution on here yet.
It was basically a typo...
In my Json decoder i use 2 Do while statements with
while (b >= 0x20);
In the second Do While statement i forgot the "=".
Therefore it wasn't rendering correctly...
thanks
I believe that you are creating your LatLng objects from overview_polyline. This, according to Google documentation "contains an object holding an array of encoded points that represent an approximate (smoothed) path of the resulting directions.".
I'm pretty sure that you can get a more detailed route building your LatLng object based on legs[] and steps[] data as the official documentation states that A step is the most atomic unit of a direction's route, containing a single step describing a specific, single instruction on the journey.
Take a look at:
https://developers.google.com/maps/documentation/directions/#Routes
Tmichel,
the Michael has the correctly wave, because on legs and steps on your route plot the line out of the street.
Legs and steps, has informations around coordinates for informations to alert the user.
Polylines are the correct and precise points over the street.
Sorry my bad english
Related
I am trying to extract several images url constructed from parts of a JSON to be displayed.
I was able to retrieve the JSON and then construct several url from the JSON displaying it as a text on the screen ( String ).
at the end of the AsyncTask i used the Universal Image Loader, to display a single pic, in case the JSON contain information of a single pic, but the problem is whnen construct several url from the JSON :
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format + "/n");
it create a string of address just in separate lines ( if displayed in a textView), but bening passed to UIL it is not acceptable.
So i am not sure how to do this, since i am trying to have an image view within a listView in a linearway or differently maybe, to display several images, depending on the JSON information .
Any suggestion on how to do this will be great .
My AsyncTask code it;
public class JsonTask extends AsyncTask<String, String, String> {
#Override
protected String doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
StringBuffer finalBufferData = new StringBuffer();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
String publicID = finalObject.getString("public_id");
String version = finalObject.getString("version");
String format = finalObject.getString("format");
finalBufferData.append("http://res.cloudinary.com/CLOUD_NAME/" + fileType +
"/upload/v" + version + "/" + publicID + "." + format);
}
return finalBufferData.toString();
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
ImageLoader.getInstance().displayImage(result, imageViewDisplayUp);
//imagesList.setText(result);
}
}
}
found a way around it, by adding another String which is not in the JSON but get created from other JASON strings.
Since the public_id, version, and format are in the JSON downloaded from Cloudinary and needed to build the right address for the images to be passed into the ImageLoader, and i couldnt not find another way to retrieve a list of images urls uploaded by the user with a specific tag to Cloudinary, without using the admin api which require writing api_secret in the program, i ended up doing the following;
public class JsonTask extends AsyncTask<String, String, List<upImgModels> > {
#Override
protected List<upImgModels> doInBackground(String... params) {
HttpURLConnection connection = null;
BufferedReader reader = null;
try {
URL url = new URL(params[0]);
connection = (HttpURLConnection) url.openConnection();
connection.connect();
InputStream stream = connection.getInputStream();
reader = new BufferedReader(new InputStreamReader(stream));
StringBuffer buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
String finalJson = buffer.toString();
JSONObject parentObject = new JSONObject(finalJson);
JSONArray parentArray = parentObject.getJSONArray("resources");
List<upImgModels> upImgList = new ArrayList<>();
for(int i=0; i<parentArray.length(); i++) {
JSONObject finalObject = parentArray.getJSONObject(i);
upImgModels upImgModels = new upImgModels();
upImgModels.setPublic_id(finalObject.getString("public_id"));
upImgModels.setVersion(finalObject.getString("version"));
upImgModels.setFormat(finalObject.getString("format"));
upImgModels.setAddress("http://res.cloudinary.com/we4x4/" + fileType
+ "/upload/v" + finalObject.getString("version") + "/"
+ finalObject.getString("public_id") + "." +
finalObject.getString("format"));
upImgList.add(upImgModels);
}
return upImgList;
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (JSONException e) {
e.printStackTrace();
} finally {
if (connection != null) {
connection.disconnect();
}
try {
if (reader != null) {
reader.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onPostExecute(List<upImgModels> result) {
super.onPostExecute(result);
upImgAdapter adapter = new upImgAdapter(getApplicationContext(), R.layout.row, result);
listViewUpload.setAdapter(adapter);
//imagesList.setText(result);
}
}
public class upImgAdapter extends ArrayAdapter{
public List<upImgModels> upImgModelsList;
private int resource;
private LayoutInflater inflater;
public upImgAdapter(Context context, int resource, List<upImgModels> objects) {
super(context, resource, objects);
upImgModelsList = objects;
this.resource = resource;
inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
if(convertView == null){
convertView = inflater.inflate(R.layout.row, null);
}
ImageView imageViewDisplay;
imageViewDisplay = (ImageView)convertView.findViewById(R.id.imageViewDisplay);
ImageLoader.getInstance().displayImage(upImgModelsList.get(position).getAddress(), imageViewDisplay);
return convertView;
}
}
}
I hope someone could suggest a better way to do this if it is possible, which i am sure that is the case.
I want to retrieve some data from mysql in php and store it in array and then in Android I want to use that data. For example I want to retrieve the location of multiple people whose profession id = 1 (let's say) and then in Android I want to show that locations on map. I don't know how to do this. I have the following PHP and Android files which don't work. Please help.
<?php
require "config.php";
$pro_id=1;
$sql="SELECT user.first_name, current_location.crtloc_lat,current_location.crtloc_lng FROM user INNER JOIN current_location
where user.user_id=current_location.user_id AND user.pro_id='$pro_id'";
//$sql = "select * from current_location where user_id=76";
$res = mysqli_query($con,$sql);
$result = array();
while($row = mysqli_fetch_array($res)){
array_push($result,
array('lat'=>$row[3],
'lan'=>$row[4]
));
}
echo json_encode(array("result"=>$result));
mysqli_close($con);
and android activity
public void searchProfession(){
JSONObject myJson = null;
try {
// http://androidarabia.net/quran4android/phpserver/connecttoserver.php
// Log.i(getClass().getSimpleName(), "send task - start");
HttpParams httpParams = new BasicHttpParams();
//
HttpParams p = new BasicHttpParams();
// p.setParameter("name", pvo.getName());
// p.setParameter("user", "1");
p.setParameter("profession",SearchProfession);
// Instantiate an HttpClient
HttpClient httpclient = new DefaultHttpClient(p);
String url = "http://abh.netai.net/abhfiles/searchProfession.php";
HttpPost httppost = new HttpPost(url);
// Instantiate a GET HTTP method
try {
Log.i(getClass().getSimpleName(), "send task - start");
//fffffffffffffffffffffffffff
httppost.setHeader("Content-type", "application/json");
InputStream inputStream = null;
String result = null;
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
inputStream = entity.getContent();
// json is UTF-8 by default
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
// BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null)
{
sb.append(line + "\n");
}
result = sb.toString();
myJSON=result;
// return JSON String
if(inputStream != null)inputStream.close();
//ffffffffffffffffffffffffffff
//
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("user", "1"));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
ResponseHandler<String> responseHandler = new BasicResponseHandler();
String responseBody = httpclient.execute(httppost,
responseHandler);
// Parse
JSONObject json = new JSONObject(myJSON);
JSONArray jArray = json.getJSONArray("result");
ArrayList<HashMap<String, String>> mylist =
new ArrayList<HashMap<String, String>>();
for (int i = 0; i < jArray.length(); i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = jArray.getJSONObject(i);
String lat = e.getString("lat");
String lan = e.getString("lan");
map.put("lat",lat);
map.put("lan",lan);
mylist.add(map);
Toast.makeText(MapsActivity.this, "your location is"+lat+","+lan, Toast.LENGTH_SHORT).show();
}
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Log.i(getClass().getSimpleName(), "send task - end");
} catch (Throwable t) {
Toast.makeText(this, "Request failed: " + t.toString(),
Toast.LENGTH_LONG).show();
}
Dear imdad: The Problem lies in you json file.
{"[]":{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"}, {"user_id":"76","crtloc_lat":"34.769604","crtloc_lng":"72.361092"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}}
The Object is empty give it some name like here is response. Change it as:
{"response":[{"user_id":"77","crtloc_lat":"34.769638","crtloc_lng":"72.361145"},{"user_id":"76","crtloc_lat":"34.769604","crtloc_lng":"72.361092"},{"user_id":"87","crtloc_lat":"33.697117","crtloc_lng":"72.976631"}]}
I have 175 mp4 files. When I process file from index 0 to index 65 (or 66), I get exception:
java.lang.IllegalArgumentException: setDataSource failed: status = 0xFFFFFFFF
at wseemann.media.FFmpegMediaMetadataRetriever.setDataSource(Native Method)
at com.jni.utils.Mp4ParserUsingFFMpeg.createThumbnail(Mp4ParserUsingFFMpeg.java:518)
at com.example.readmdtfile.activity.MainActivity$createMp4Async.createThumbnail(MainActivity.java:71)
at com.example.readmdtfile.activity.MainActivity$createMp4Async.doInBackground(MainActivity.java:55)
at com.example.readmdtfile.activity.MainActivity$createMp4Async.doInBackground(MainActivity.java:1)
at android.os.AsyncTask$2.call(AsyncTask.java:288)
at java.util.concurrent.FutureTask.run(FutureTask.java:237)
at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
at java.lang.Thread.run(Thread.java:841)
If I run process from index 65 (or nearby), processing file 65 is successful. But it still get exception sometimes
Here is code which i'm using:
public static Bitmap createThumbnail (String videoPath) {
FFmpegMediaMetadataRetriever retriever = new FFmpegMediaMetadataRetriever();
Bitmap bitmap = null;
try {
retriever.setDataSource(videoPath); //file's path
String key;
String value;
for (int i = 0; i < MetadataKey.METADATA_KEYS.length; i++) {
key = MetadataKey.METADATA_KEYS[i];
value = retriever.extractMetadata(key);
if (value != null) {
// metadata.add(new Metadata(key, value));
Log.i(TAG, "Key: " + key + " Value: " + value);
}
}
bitmap = retriever.getFrameAtTime();
if (bitmap != null) {
Log.d(TAG, "Extracted frame");
Bitmap b2 = retriever.getFrameAtTime(4000000,
FFmpegMediaMetadataRetriever.OPTION_CLOSEST_SYNC);
if (b2 != null) {
bitmap = b2;
}
} else {
Log.d(TAG, "Failed to extract frame");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
retriever.release();
}
return bitmap;
}
https://github.com/wseemann/FFmpegMediaMetadataRetriever/issues/59
Please help me.
The error is simple, an IllegalArgumentException means the video URI is invalid, if this occurs an exception is thrown. Verify the URI is valid before attempting to use it with FFmpegMediaMetadataRetriever.
The error is simple, an RuntimeException means the video URI is invalid. Verify the valid Video URI with .mp4 format, before attempting to use it with FFmpegMediaMetadataRetriever.
ImageView thumbnail1 = (ImageView) findViewById(R.id.video1);
thumbnail1.setImageBitmap(retriveVideoFrameFromVideo("http://techslides.com/demos/sample-videos/small.mp4"));
public Bitmap retriveVideoFrameFromVideo(String videoPath) {
Bitmap bitmap = null;
MediaMetadataRetriever mediaMetadataRetriever = null;
try {
mediaMetadataRetriever = new MediaMetadataRetriever();
if (Build.VERSION.SDK_INT >= 14)
mediaMetadataRetriever.setDataSource(videoPath, new HashMap<String, String>());
else
mediaMetadataRetriever.setDataSource(videoPath);
// mediaMetadataRetriever.setDataSource(videoPath);
bitmap = mediaMetadataRetriever.getFrameAtTime(1, MediaMetadataRetriever.OPTION_CLOSEST);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
} finally {
if (mediaMetadataRetriever != null) {
mediaMetadataRetriever.release();
}
}
return bitmap;
}
you just have to give setDataSource a String, save your path or url in a string like this:
String url;
mmr = new FFmpegMediaMetadataRetriever();
url = "http://www.stephaniequinn.com/Music/Commercial%20DEMO%20-%2009.mp3";
mmr.setDataSource(url, new HashMap<String, String>());
or:
mmr = new FFmpegMediaMetadataRetriever();
string s="path"
mmr.setDataSource(path);
I've got an app that tracks vehicles and draws a polyline of their travel path on a map. I want to convert this polyline into a route using the directions service routing. This will allow me to be able to drag the path around and manipulate it etc.
The problem is I can't think of a nice solution to this, and I'm not sure if it's possible. If I pass in the array of coordinates of the polyline to the directions service route it only draws a route using the start and the end of the polyline, it doesn't take into consideration any of the coordinates in between.
I tried to generate a 'waypoints' array using the polyline coordinates array by evenly dividing it and getting 8 coordinates in between and passing those in as the waypoints but it fails to render at all now. If I test the code using a coordinates array that was generated by drawing a route it works though, so I know the code is working. I'm presuming it fails because some of these coordinates may be slightly off the road (it's a polyline drawn from GPS positioning, so it's not 100% accurate), and Google doesn't just snap it to the nearest accepted location.
Can anyone think of a solution to this?
Here's code examples to make it a bit clearer:
// In the polyline app
var encoded_path = google.maps.geometry.encoding.encodePath(coordinate_array)
// In the route app
var coordinates = google.maps.geometry.encoding.decodePath(encoded_path);
var waypoints = [];
// Evenly get coordinates across the entire array to be used as waypoints
for (var i = 1; i <= 8; ++i) {
var index = Math.floor((coordinates.length/10) * i);
if (index >= coordinates.length - 1)
break;
waypoints.push({
'location': new google.maps.LatLng(coordinates[index].lat(), coordinates[index].lng()),
'stopover': false
});
}
var request = {
origin: coordinates[0],
destination: coordinates[coordinates.length - 1],
travelMode: google.maps.DirectionsTravelMode.DRIVING,
waypoints: waypoints
};
MapService.directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
MapService.directionsDisplay.setDirections(response);
}
});
It's been a while and there's a better answer now, the Roads API:
https://developers.google.com/maps/documentation/roads/intro
Directions API is not intended for this use case, there are several good reasons to not even try:
Waypoints that are stop-over (default) will allow any direction of travel, in or out, when snapping to the nearest road, regardless of previous/next waypoints.
Waypoints that are not stop-over (via:) will be very strict when snapping to roads, typical GPS offset will throw it off and cause ZERO_RESULTS (no route)-
Even if all waypoints work out well, the route will be the best route for a generic driver, not necessarily the route followed by the vehicle that sampled the positions used as waypoints.
If a vehicle samples a position at the intersection of 2 roads at different altitudes (elevated pass, bridge, tunnel, etc.), if the GPS offset makes the point be in the wrong road, it can throw routing wildly off.
You can use the direction api to check the waypoints when it ends at a road: Map of all points below a certain time of travel?. Then delete the others to create a route from the entire polyline.
public String makeURL (double sourcelat, double sourcelog, double destlat, double destlog ){
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString(sourcelat));
urlString.append(",");
urlString
.append(Double.toString( sourcelog));
urlString.append("&destination=");// to
urlString
.append(Double.toString( destlat));
urlString.append(",");
urlString.append(Double.toString( destlog));
urlString.append("&sensor=false&mode=driving");
return urlString.toString();
}
private List<LatLng> decodePoly(String encoded) {
List<LatLng> poly = new ArrayList<LatLng>();
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;
}
public class JSONParser {
InputStream is = null;
JSONObject jObj = null;
String json = "";
// constructor
public JSONParser() {
}
public String getJSONFromUrl(String url) {
// Making HTTP request
try {
// defaultHttpClient
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
is = httpEntity.getContent();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
json = sb.toString();
is.close();
} catch (Exception e) {
Log.e("Buffer Error", "Error converting result " + e.toString());
}
return json;
}
}
public void drawPath(String result) {
try {
//Tranform the string into a json object
final JSONObject json = new JSONObject(result);
JSONArray routeArray = json.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<LatLng> list = decodePoly(encodedString);
for(int z = 0; z<list.size()-1;z++){
LatLng src= list.get(z);
LatLng dest= list.get(z+1);
theMap.addPolyline(new PolylineOptions()
.add(src,dest)
.width(2)
.color(Color.BLUE).geodesic(true));
}
}
catch (JSONException e) {
}
}
private class connectAsyncTask extends AsyncTask<Void, Void, String>{
private ProgressDialog progressDialog;
String url;
connectAsyncTask(String urlPass){
url = urlPass;
}
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(YOUR_Activity.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
#Override
protected String doInBackground(Void... params) {
JSONParser jParser = new JSONParser();
String json = jParser.getJSONFromUrl(url);
return json;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.hide();
if(result!=null){
drawPath(result);
}
}
}
I'm about to trace with direction service the railway between two station.
The problem is I can't get the Lat/Lng of the two station, it get always a neighbour points.
The route is (search on google maps website) :
Ceres, TO to Stazione Porta Nuova, Corso Vittorio Emanuele II, 58, Torino
I need Lat/Lng of Ceres (train station) and Stazione Porta Nuova, Corso Vittorio Emanuele II, 58, Torino (train station). How can I get them?
So I can draw in my maps the same railway (brown line).
public class GetXMLTask
{
static double longitute;
static double latitude;
public JSONObject getLocationInfo(String address)
{
StringBuilder stringBuilder = new StringBuilder();
try
{
address = address.replaceAll(" ","%20");
HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1)
{
stringBuilder.append((char) b);
}
}
catch (ClientProtocolException e)
{
Log.i("getLocationInfo ClientProtocolException", e.toString());
}
catch (IOException e)
{
Log.i("getLocationInfo IOException", e.toString());
}
JSONObject jsonObject = new JSONObject();
try
{
jsonObject = new JSONObject(stringBuilder.toString());
}
catch (JSONException e)
{
Log.i("getLocationInfo JSONException", e.toString());
}
return jsonObject;
}
public ArrayList<Double> getLatLong(JSONObject jsonObject)
{
ArrayList<Double> latlng = new ArrayList<Double>();
try
{
longitute = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lng");
latitude = ((JSONArray)jsonObject.get("results")).getJSONObject(0).getJSONObject("geometry").getJSONObject("location").getDouble("lat");
latlng.add(latitude);
latlng.add(longitute);
}
catch (JSONException e)
{
longitute = 0;
latitude = 0;
Log.i("getLatLong", e.toString());
}
return latlng;
}
}
now we can call it inside our class by
latitude = new GetXMLTask().getLatLong(new GetXMLTask().getLocationInfo(address)).get(0);
longitude = new GetXMLTask().getLatLong(new GetXMLTask().getLocationInfo(address)).get(1);
I may not have the super optimised code , but this is working pretty fine for me , give it a try , just passed the address in your calling class