1

I Have some code that showing between two directions which the destination has initialized (known position). The full code like this :

package com.my.app;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;

import android.app.FragmentManager;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
//import com.google.android.gms.maps.MapFragment;
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 android.support.v4.app.FragmentActivity;
import com.google.android.gms.maps.SupportMapFragment;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationManager;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;



public class CobaMap2 extends FragmentActivity {
final int RQS_GooglePlayServices = 1;
private GoogleMap myMap;
double src_lat = -7.81016;
double src_long = 110.46860;
double dest_lat = -7.778031;
double dest_long = 110.494180;
MarkerOptions markerOptions;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout2);

myMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
myMap.setMyLocationEnabled(true);
// Set Current Location
moveToMyLocation();}
private void moveToMyLocation()
{
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
 myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), 
location.getLongitude()), 13));
}



// choose map layout

RadioGroup rgViews = (RadioGroup) findViewById(R.id.rg_views);

rgViews.setOnCheckedChangeListener(new OnCheckedChangeListener() {

    @Override
    public void onCheckedChanged(RadioGroup group, int checkedId) {
        if(checkedId == R.id.rb_normal){
            myMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        }else if(checkedId == R.id.rb_satellite){
            myMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
        }else if(checkedId == R.id.rb_terrain){
            myMap.setMapType(GoogleMap.MAP_TYPE_TERRAIN);
        }

    }
});




LatLng srcLatLng = new LatLng(src_lat, src_long);
LatLng destLatLng = new LatLng(dest_lat, dest_long);

myMap.addMarker(new MarkerOptions()
.position(srcLatLng).title("Source place"));

myMap.animateCamera(CameraUpdateFactory.newLatLng(srcLatLng));

myMap.addMarker(new MarkerOptions()
.position(destLatLng).title("Destination place"));

// Enabling MyLocation in Google Map
myMap.setMyLocationEnabled(true);
myMap.getUiSettings().setZoomControlsEnabled(true);
myMap.getUiSettings().setCompassEnabled(true);
myMap.getUiSettings().setMyLocationButtonEnabled(true);
myMap.getUiSettings().setAllGesturesEnabled(true);
myMap.setTrafficEnabled(true);
myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(srcLatLng,12));
        markerOptions = new MarkerOptions();


// Polyline line = myMap.addPolyline(new PolylineOptions().add(srcLatLng, destLatLng).width(5).color(Color.RED));

connectAsyncTask _connectAsyncTask = new connectAsyncTask();
         _connectAsyncTask.execute();

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.cobamap, menu);
return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_legalnotices:
String LicenseInfo = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(
getApplicationContext());
AlertDialog.Builder LicenseDialog = new AlertDialog.Builder(CobaMap2.this);
LicenseDialog.setTitle("Legal Notices");
LicenseDialog.setMessage(LicenseInfo);
LicenseDialog.show();
return true;
}
return super.onOptionsItemSelected(item);
}

@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();

int resultCode = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getApplicationContext());

if (resultCode == ConnectionResult.SUCCESS){
Toast.makeText(getApplicationContext(),
"isGooglePlayServicesAvailable SUCCESS",
Toast.LENGTH_LONG).show();
}else{
GooglePlayServicesUtil.getErrorDialog(resultCode, this, RQS_GooglePlayServices);
}

}

private class connectAsyncTask extends AsyncTask<Void, Void, Void>{
private ProgressDialog progressDialog;

@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
progressDialog = new ProgressDialog(CobaMap2.this);
progressDialog.setMessage("Fetching route, Please wait...");
progressDialog.setIndeterminate(true);
progressDialog.show();
}
@Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
fetchData();
return null;
}
@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if(doc!=null){
NodeList _nodelist = doc.getElementsByTagName("status");
Node node1 = _nodelist.item(0);
String _status1 = node1.getChildNodes().item(0).getNodeValue();
if(_status1.equalsIgnoreCase("OK")){
NodeList _nodelist_path = doc.getElementsByTagName("overview_polyline");
Node node_path = _nodelist_path.item(0);
Element _status_path = (Element)node_path;
NodeList _nodelist_destination_path = _status_path.getElementsByTagName("points");
Node _nodelist_dest = _nodelist_destination_path.item(0);
String _path = _nodelist_dest.getChildNodes().item(0).getNodeValue();
List<LatLng> directionPoint = decodePoly(_path);

PolylineOptions rectLine = new PolylineOptions().width(10).color(Color.BLUE);
for (int i = 0; i < directionPoint.size(); i++) {
rectLine.add(directionPoint.get(i));
}
// Adding route on the map
myMap.addPolyline(rectLine);
markerOptions.position(new LatLng(dest_lat, dest_long));
markerOptions.draggable(true);
myMap.addMarker(markerOptions);
}else{
showAlert("Unable to find the route");
}


}else{
showAlert("Unable to find the route");
}

progressDialog.dismiss();

}

}

Document doc = null;
private void fetchData()
{   
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps/api/directions/xml?origin=");
urlString.append(src_lat);
urlString.append(",");
urlString.append(src_long);
urlString.append("&destination=");//to
urlString.append(dest_lat);
urlString.append(",");
urlString.append(dest_long);
urlString.append("&sensor=true&mode=driving");
Log.d("url","::"+urlString.toString());
HttpURLConnection urlConnection= null;
URL url = null;
try
{
url = new URL(urlString.toString());
urlConnection=(HttpURLConnection)url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoOutput(true);
urlConnection.setDoInput(true);
urlConnection.connect();
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
doc = (Document) db.parse(urlConnection.getInputStream());//Util.XMLfromString(response);
}catch (MalformedURLException e){
e.printStackTrace();
}catch (IOException e){
e.printStackTrace();
}catch (ParserConfigurationException e){
e.printStackTrace();
}
catch (SAXException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}


private void showAlert(String message){
AlertDialog.Builder alert = new AlertDialog.Builder(CobaMap2.this);
alert.setTitle("Error");
alert.setCancelable(false);
alert.setMessage(message);
alert.setPositiveButton("Ok",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub

}
});
alert.show();
}

private ArrayList<LatLng> decodePoly(String encoded) {
ArrayList<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 position = new LatLng((double) lat / 1E5, (double) lng / 1E5);
poly.add(position);
}
return poly;
}
}

The code worked perfectly, You can see between two location (source and destination) are known location. then i need change the first location (source location) with my current Location, and current location detected by this code :

// Set Current Location
moveToMyLocation();}
private void moveToMyLocation()
{
LocationManager locationManager = (LocationManager)
getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));
if (location != null)
{
 myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), 
location.getLongitude()), 13));
}

And code to initialized the location is :

LatLng srcLatLng = new LatLng(src_lat, src_long);
    LatLng destLatLng = new LatLng(dest_lat, dest_long);

The problem is, how to passing data from my current location to set the data for the source location and show path between location. (Source : My current Location, Destination : Known Location). What the method must i use ?. I mean the app show from my current location to destination location with modify that code ?

user2285197
  • 33
  • 2
  • 9

1 Answers1

0

Check this question

How to draw interactive Polyline on route google maps v2 android

in this you will get the code to draw a proper route from one place to another using polyLine, also includes current and destination location !

Edit :

Use

src_lat=location.getLatitude() 
src_long=location.getLongitude()

inside

if (location != null)
{
src_lat=location.getLatitude() 
src_long=location.getLongitude()
 myMap.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), 
location.getLongitude()), 13));
}

Edit: try by Changing :

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, false));

to

Location location = locationManager.getLastKnownLocation(locationManager.getBestProvider(criteria, true));
Community
  • 1
  • 1
Tarsem Singh
  • 14,139
  • 7
  • 51
  • 71
  • Thanks for the answer, but i prefer use this code because some reason. And i have no idea what must i do, im very new on android developed :( – user2285197 Jul 12 '13 at 18:06
  • ok than please let me know what do you actually want to do with this ? do you want to set current location as source location and destination location is already known ? or something else ? – Tarsem Singh Jul 12 '13 at 18:08
  • Yes, like that. i want my current location as my source location. Modify from my source, not from other source. Can you help me ? – user2285197 Jul 12 '13 at 18:12
  • Yep, i have tried yor answer, but warning says "Unable to Find the route", i think the problem is when i change the value of source lat and lng to zero like `double src_lat = 0; double src_long = 0;` is the declarated of `src_lat` and `src_long` correct ? – user2285197 Jul 12 '13 at 18:32
  • it means you are not able to get your current location using location manager ! is camera animating to current location ? – Tarsem Singh Jul 12 '13 at 18:34
  • `myMap.animateCamera(CameraUpdateFactory.newLatLngZoom( new LatLng(location.getLatitude(), location.getLongitude()), 13));` < i use this gor animating camera when button my location on map tap/press. how ? – user2285197 Jul 12 '13 at 18:39
  • ok it means you are not getting current location using location manager, because it should automatically animate as per your code ! let me check that why are you not getting current location ! – Tarsem Singh Jul 12 '13 at 18:42
  • I Have deleted code for animate camera to current location, but the error still same. The logcat says : `07-13 01:46:30.845: I/MotionRecognitionManager(23075): .unregisterListener : / listener count = 0->0, listener=android.widget.AbsListView$4@420b9f78 07-13 01:46:32.630: E/SpannableStringBuilder(23075): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length 07-13 01:46:32.630: E/SpannableStringBuilder(23075): SPAN_EXCLUSIVE_EXCLUSIVE spans cannot have a zero length` – user2285197 Jul 12 '13 at 18:48
  • the error is no existing there ! so there is no need to delete that code wait for 2 mins i am just checking your code out ! – Tarsem Singh Jul 12 '13 at 18:49
  • check updated Answer and see if you are now able to get current Location ! try Testing by log Cat ! – Tarsem Singh Jul 12 '13 at 18:56
  • I Have no reputation to vote-up. So sorry, next when my reputation up i will vote! – user2285197 Jul 12 '13 at 19:10