I've been trying to add my GeoPoints to the itemizedOverlay Array in order to draw the points on the map. Unfortunately, the app crashing at this point.
My Code:
package com.example.phooogle;
public class GoogleMapsAppActivity extends MapActivity {
private MapView mapView;
private MapController mc;
private MyLocationOverlay myLocationOverlay;
private myMapService mms;
String[] ms;
private LocationManager lm;
private LocationListener locationListener;
private MyLocationOverlay myLocOverlay;
GeoPoint p;
GeoPoint progress1[];
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
int latitude;
int longitude;
private ProgressDialog progress;
MotionEvent event;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_cool_map);
progress= new ProgressDialog(this);
progress.setIndeterminate(true);
progress.setMessage("I am thinking");
InitTask init_task= new InitTask();
init_task.execute("144.963620993985", "-37.8140023779914", "20", "Litter Bin");
try {
String[] arrs = init_task.strArr2;
//Log.d(" print points", " Array Size " + arrs.length);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
for(int j=0; j<arrs.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(arrs[j]);
y = Double.parseDouble(arrs[j+1]);
//Log.d(" print points", "lat " + x + " long" + y);
itemizedOverlay.addOverlayItem((int) x , (int) y , "La trobe");
mapView.getOverlays().add(itemizedOverlay );
}
}
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
/*
Drawable makerDefault = this.getResources().getDrawable(R.drawable.poke);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
itemizedOverlay.addOverlayItem(init_task.geoPointsArray, "La trobe");
mapView.getOverlays().add(itemizedOverlay );
MapController mc = mapView.getController();
mc.setCenter(new GeoPoint((int) (1E6 * -37.720754), (int) (1E6 * 145.048798))); // Some where .
mc.zoomToSpan(itemizedOverlay.getLatSpanE6(), itemizedOverlay.getLonSpanE6());
for (int i = 0; i < geoPointsArray.size() ; i++)
{
Log.d(" print points", " points " + geoPointsArray.get(i));
}*/
// Log.d(" print points", " Size " + init_task.geoPointsArray.size());
/*
mapView = (MapView) findViewById(R.id.mapview);
List<Overlay> mapOverlays = mapView.getOverlays();
//add any icon here for the marker
Drawable drawable = GoogleMapsAppActivity.this.getResources().getDrawable(R.drawable.poke);
MapViewItemizedOverlay itemizedOverlay = new MapViewItemizedOverlay(drawable,this);
//use your array here instead
//GeoPoint point1 = new GeoPoint(lat,lng);
OverlayItem overlayitem1 = new OverlayItem(point1, "Info", "You are here!" );
itemizedOverlay.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay);
*/
}
private void initMap()
{
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// mapView.setStreetView(true);
mc = mapView.getController();
}
public void theRouteDraw(GeoPoint p){
mc.animateTo(p);
mc.setZoom(13);
mapView.invalidate();
mapView.setSatellite(true);
}
private void initMyLocation() {
myLocOverlay = new MyLocationOverlay(this, mapView);
myLocOverlay.enableMyLocation();
mapView.getOverlays().add(new myLocOverlay());
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class myLocOverlay extends Overlay{
public void draw(Canvas canvas, MapView mapv, boolean shadow){
super.draw(canvas, mapv, shadow);
Projection projection = mapView.getProjection();
Path p1 = new Path();
for (int i = 0; i < geoPointsArray.size(); i++) {
if (i == geoPointsArray.size() - 1) {
break;
}
Point from = new Point();
Point to = new Point();
projection.toPixels(geoPointsArray.get(i), from);
projection.toPixels(geoPointsArray.get(i + 1), to);
p1.moveTo(from.x, from.y);
p1.lineTo(to.x, to.y);
}
Paint mPaint = new Paint();
mPaint.setStyle(Style.STROKE);
mPaint.setColor(Color.BLACK);
mPaint.setAntiAlias(true);
mPaint.setStrokeWidth(4);
canvas.drawPath(p1, mPaint);
super.draw(canvas, mapView, shadow);
}
}
private class InitTask extends AsyncTask<String, GeoPoint, List<GeoPoint>> {
List<GeoPoint> geoPointsArray = new ArrayList<GeoPoint>();
GeoPoint p;
private ProgressDialog progressDialog;
private String rst = " " ;
private String[] strArr1;
private String[] strArr2;
protected void onPreExecute() {
//progress.show();
}
#Override
protected List<GeoPoint> doInBackground(String... arg0) {
String result = "";
int responseCode = 0;
int executeCount = 0;
HttpResponse response;
StringBuilder sb = new StringBuilder();
String line;
try
{
HttpClient client = new DefaultHttpClient();
HttpGet httppost = new HttpGet("http://xxxx/ccvo/mel-asset-data/query.php?lon="+ arg0[0].toString() + "&lat="+ arg0[1].toString() +"&within=" + arg0[2].toString() + "&keyword="+ arg0[3].toString().replace(" ", "%20"));
do
{
// progressDialog.setMessage("Passing paratmeters.. ("+(executeCount+1)+"/5)");
// Execute HTTP Post Request
executeCount++;
response = client.execute(httppost);
responseCode = response.getStatusLine().getStatusCode();
} while (executeCount < 5 && responseCode == 408);
BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
while ((line = rd.readLine()) != null)
{
result = line.trim();
sb.append(line);
}
}catch (Exception e2) {
responseCode = 408;
e2.printStackTrace();
}
rst = result.toString();
// splits everything
if(rst != null && rst.length() > 0)
{
strArr1 = rst.split("\\|");
for(int i=0;i<strArr1.length;i++)
{
// Log.d("Results", "Array size1.1 " + i);
Log.v("Results", "Array split1.2 " + strArr1[i] );
if(strArr1[i] != null && strArr1[i].length() >0 && strArr1[i].contains(","))
{
strArr2 = strArr1[i].split(",");
for(int j=0; j<strArr2.length ;j++)
{
double y =0;
double x =0;
if(j == 1)
{
/// x
//Log.d("Results", "2If statem " + strArr2[j] );
x = Double.parseDouble(strArr2[j]);
y = Double.parseDouble(strArr2[j+1]);
geoPointsArray.add(new GeoPoint((int)(x*1e6), (int)(y*1e6)));
Log.d("geoPointsArray", "geoPointsArray " + geoPointsArray.toString() );
}
}
}
}
}
return geoPointsArray;
}
#Override
protected void onProgressUpdate(GeoPoint... progress1) {
theRouteDraw(progress1[0]);
geoPointsArray.add(progress1[0]);
int lon=progress1[0].getLongitudeE6();
int lat=progress1[0].getLatitudeE6();
GeoPoint p2=new GeoPoint(lon,lat);
geoPointsArray.add(p2);
initMyLocation();
}
#Override
protected void onPostExecute(List<GeoPoint> geoPointsArray)
{
//super.onPostExecute(geoPointsArray);
progress.dismiss();
//startActivity(i);
//i.getCharExtra("Geop", geoPointsArray);
Log.d("Lista", " check " + geoPointsArray.size());
// theRouteDraw(geoPointsArray);
}
}
}
My MirItemizedOverlay Class:
class MirItemizedOverlay extends ItemizedOverlay {
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
mOverlays.add(overlayItem);
populate();
}
#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();
}
return false;
}
private Context getBaseContext() {
// TODO Auto-generated method stub
return null;
}
public void addOverlayItem(int lat, int lon, String title) {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
/* public void addOverlayItem(GeoPoint point , String title) {
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
//GeoPoint point = new GeoPoint(lat, lon);
}*/
}
The error :
: E/AndroidRuntime(2752): FATAL EXCEPTION: main
: E/AndroidRuntime(2752): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.phooogle/com.example.phooogle.GoogleMapsAppActivity}: java.lang.NullPointerException
: E/AndroidRuntime(2752): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
: E/AndroidRuntime(2752): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
: E/AndroidRuntime(2752): at android.app.ActivityThread.access$600(ActivityThread.java:130)
: E/AndroidRuntime(2752): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
: E/AndroidRuntime(2752): at android.os.Handler.dispatchMessage(Handler.java:99)
: E/AndroidRuntime(2752): at android.os.Looper.loop(Looper.java:137)
: E/AndroidRuntime(2752): at android.app.ActivityThread.main(ActivityThread.java:4745)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invokeNative(Native Method)
: E/AndroidRuntime(2752): at java.lang.reflect.Method.invoke(Method.java:511)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
: E/AndroidRuntime(2752): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
: E/AndroidRuntime(2752): at dalvik.system.NativeStart.main(Native Method)
: E/AndroidRuntime(2752): Caused by: java.lang.NullPointerException
: E/AndroidRuntime(2752): at com.example.phooogle.GoogleMapsAppActivity.onCreate(GoogleMapsAppActivity.java:68)
I've tried several ways to do like I tried to change the addOverlayItem method to accept the GeoPoitns from the AsyncTask return but also failed. I almost gave me on this. :)
Update
The problem resolved. Here is the fix:
try {
//String[] arrs = init_task.strArr2;
List<GeoPoint> geoL = init_task.get();
//Log.d(" Get the size " , " Geo List " + geoL.get(1).toString());
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mc = mapView.getController();
List<Overlay> listOfOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.poke);
MyItemizedOverlay itemizedoverlay = new MyItemizedOverlay(drawable, this);
for ( int i = 0; i < geoL.size() ; i++)
{
OverlayItem overlayitem1 = new OverlayItem(geoL.get(i), Selectedword + "s found! " , "It's withing " + selectedDistance + " To your position");
itemizedoverlay.addOverlay(overlayitem1);
listOfOverlays.add(itemizedoverlay);
}
//mc.animateTo(geoL.get(1));
mc.setCenter(new GeoPoint((int) (1E6 * gps.getLatitude() ), (int) (1E6 * gps.getLongitude() ))); // Some where .
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {}
initMap();
initMyLocation();
// theRouteDraw();
Your issue is that mapView is null, you haven't called initMap() yet. This causes mapView.getOverlays().add(itemizedOverlay ); to fail.
Related
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;
}
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);
}
In my mapview, Used geocding inside SingleTapUp.
Whenever zoom controls of mapview are used, singleTapUp also gets invoked.
Any suggestions to overcome this scenario.
The code in my main method
public static TextView info;
private MapController mapController;
private MapView mapView;
public LocationManager orgManager;
private MyOverlays itemizedoverlay, blackmarker;
public boolean gps_enabled = false;
public boolean network_enabled = false;
public Criteria c;
public String bestProvider;
public double orginLongitude, orginLatitude, destLongtitude, destLatitude,
currLatitude, currLongtitude, lat, lon;
public boolean isLongPress= false, GPSfix = false;
Location originLocation = new Location("source");
Location currLocation = new Location("current");
Location destinationLocation = new Location("destination");
Location fixlocation= new Location("fix");
NotificationManager nm;
Vibrator v;
MediaPlayer mp = new MediaPlayer();
private TextToSpeech myTTS;
private int MY_DATA_CHECK_CODE = 0;
private List<Overlay> mapOverlays;
private Projection projection;
GestureDetector gestureScanner;
long lastGesture = System.currentTimeMillis();
GeoPoint markerPoint = null;
private int count = 0;
MyLocationOverlay mo;
public GeoPoint source;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_layout);
info = (TextView) findViewById(R.id.infopane);
mapView = (MapView) findViewById(R.id.mapView);
//Button myloc = (Button)findViewById(R.id.myloc);
info.setText("Please Tap on the Map");
orgManager = (LocationManager) this
.getSystemService(Context.LOCATION_SERVICE);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
markerPoint = null;
mapController = mapView.getController();
mapController.setZoom(16); // Zoom 1 is world view
mapView.invalidate();
mo = new MyLocationOverlay(MapClass.this, mapView);
mapView.getOverlays().add(mo);
mapOverlays = mapView.getOverlays();
projection = mapView.getProjection();
Drawable drawable = this.getResources()
.getDrawable(R.drawable.mark_red);
Drawable black_marker = this.getResources().getDrawable(
R.drawable.marker_black);
itemizedoverlay = new MyOverlays(drawable);
blackmarker = new MyOverlays(black_marker);
try {
gps_enabled = orgManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
Log.i("success", "Gps:" + String.valueOf(gps_enabled)+ "N/w:" + String.valueOf(network_enabled) );
} catch (Exception ex) {
Log.i("sample", "sample");
}
if (!gps_enabled) {
Log.i("failure", "Gps:" + String.valueOf(gps_enabled)+ "N/W:" + String.valueOf(network_enabled) );
final AlertDialog.Builder builder = new AlertDialog.Builder(MapClass.this);
builder.setTitle("Attention!");
builder.setMessage("Sorry, location is not determined. Please open app after enabling GPS & wireless networks").setCancelable(false).setPositiveButton("OK", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
finish();
}
});
AlertDialog alert = builder.create();
alert.show();
}
if(gps_enabled){
orgManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
fixlocation = orgManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
Log.i("fix", String.valueOf(fixlocation.getLatitude() + fixlocation.getLongitude()));
if (fixlocation!=null){
originLocation.setLatitude(fixlocation.getLatitude());
originLocation.setLongitude(fixlocation.getLongitude());
Log.i("origin fix", String.valueOf(originLocation.getLatitude() + originLocation.getLongitude()));
GPSfix = true;
}else Toast.makeText(MapClass.this, "", Toast.LENGTH_SHORT).show();
}
if (GPSfix) {
// double a = originLocation.getLatitude();
// double b = originLocation.getLongitude();
source = new GeoPoint(
(int) ((fixlocation.getLatitude()) * 1E6),
(int) ((fixlocation.getLongitude()) * 1E6));
mapController.animateTo(source);
mapView.getMapCenter();
createMarker();
Toast.makeText( MapClass.this," Source GPS Values Latitude: "
+ fixlocation.getLatitude() + " Longitude: "
+ fixlocation.getLongitude(), Toast.LENGTH_SHORT).show();
}
else Toast.makeText(MapClass.this, "Wait for GPS", Toast.LENGTH_SHORT).show();
gestureScanner = new GestureDetector(this, this);
}
The code in gesture scanner method.
onLongPress
#Override
public void onLongPress(final MotionEvent e) {
// TODO Auto-generated method stuMapClass Toast.makeText(MapClass.this,
// "LongPress", Toast.LENGTH_SHORT)
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MapClass.this);
// Setting Dialog Title
alertDialog.setTitle("Alert!!");
// Setting Dialog Message
alertDialog.setMessage("Do you want to select this as destination");
// Setting Positive "Yes" Button
alertDialog.setPositiveButton("YES",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
String add = "";
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) e.getX(), (int) e.getY());
// latitude
lat = geopoint.getLatitudeE6() / 1E6;
// longitude
lon = geopoint.getLongitudeE6() / 1E6;
Geocoder geoCoder = new Geocoder(getBaseContext(),
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.getLongitudeE6() / 1E6, 1);
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 ioe) {
ioe.printStackTrace();
}
mapOverlays.add(new MyOverlay((originLocation
.getLatitude()),
(originLocation.getLongitude()), lat, lon));
destinationLocation.setLatitude(lat);
destinationLocation.setLongitude(lon);
String distance = Float.toString((originLocation
.distanceTo(destinationLocation) / 1000));
createblack();
count++;
Toast.makeText(getBaseContext(), distance + "kms",
Toast.LENGTH_SHORT).show();
info.setText("Selected destination is " + "\n" + add
+ "\n" + " The journey distance is " + distance
+ " Kms ");
mapView.postInvalidate();
isLongPress = true;
mapController.animateTo(source);
mapView.getMapCenter();
}
private void createblack() {
// TODO Auto-generated method stub
GeoPoint p = new GeoPoint((int) (lat * 1E6),
(int) (lon * 1E6));
OverlayItem overlayitem = new OverlayItem(p,
"Destination", "");
blackmarker.addOverlay(overlayitem);
mapView.getOverlays().add(blackmarker);
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog
Toast.makeText(getApplicationContext(),
"You clicked on NO", Toast.LENGTH_SHORT).show();
dialog.cancel();
}
});
// Showing Alert Message
alertDialog.show();
}
OnsingeTapup
#Override
public boolean onSingleTapUp(MotionEvent arg0) {
// TODO Auto-generated method stub
Log.i("SingleTap", arg0.toString());
GeoPoint geopoint = mapView.getProjection().fromPixels(
(int) arg0.getX(), (int) arg0.getY());
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
geopoint.getLatitudeE6() / 1E6,
geopoint.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";
}
if (count == 0) {
info.setText("The location you have selected is" + "\n" + add
+ "\n" + "To confirm it longpress the location");
} else
Toast.makeText(getBaseContext(), add, Toast.LENGTH_SHORT)
.show();
} catch (IOException ioe2) {
ioe2.printStackTrace();
}
return true;
}
Additionally used a Overlay Class to place markers..
It is a bit hard to debug your code as there are important parts missing but I would suggest taking a look at the following answer to a similar StackOverflow question:
https://stackoverflow.com/a/2990749/376016
The proposed solution for recognising gestures on the MapView is to create a custom Overlay that only handles touch events and insert it as the first overlay. Using this approach I was able to create a small test application that used most of your code and correctly ignored the pinch to zoom gestures on the MapView.
I'm trying to apply the tutorial: http://deckjockey.blogspot.com/2010/01/android-baloon-display-on-map.html?showComment=1322215574598#c3178096297154271518 on my code, and I'm facing a small difficulty - it doesn' work,
here is my code:
public void HuntCl(View v) throws UnknownHostException, IOException{
String sentenceX, sentenceY = null;
try {
clientSocket = new Socket("10.0.2.2", 1234);
Log.d("LatitudeE6", ""+point.getLatitudeE6());
Log.d("LongitudeE6", ""+point.getLongitudeE6());
DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());
BufferedReader inFromServer = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
sentenceX = ""+point.getLatitudeE6();
sentenceY = ""+point.getLongitudeE6();
outToServer.writeBytes(sentenceX + " "+ sentenceY+'\n');
String ciekawostka = inFromServer.readLine();
String [] holder = ciekawostka.split("\\s+");
for(int i =0; i<holder.length; i++){
x = Integer.valueOf(holder[i]);
y= Integer.valueOf(holder[i+1]);
marker=getResources().getDrawable(R.drawable.pin);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
POI funPlaces = new POI(marker,x,y);
mapView.getOverlays().add(funPlaces);
GeoPoint pt = funPlaces.getCenter();
mapView.getController().setCenter(pt);
}
} catch (Exception e) {
Log.d("error","TCP Error: " + e.toString());
}
}
class POI extends ItemizedOverlay {
private List<OverlayItem> locations = new ArrayList<OverlayItem>();
private Drawable marker;
public POI(Drawable marker, int tX, int tY)
{
super(marker);
this.marker=marker;
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
BaloonLayout noteBaloon = (BaloonLayout) layoutInflater.inflate(R.layout.ballon, null);
RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(200,100);
layoutParams.addRule(RelativeLayout.CENTER_VERTICAL);
layoutParams.addRule(RelativeLayout.CENTER_HORIZONTAL);
noteBaloon.setLayoutParams(layoutParams);
mapView.removeView(noteBaloon);
noteBaloon.setVisibility(View.VISIBLE);
// TextView textmsg = (TextView) noteBaloon.findViewById(R.id.note_text);
TextView textmsg = (TextView) noteBaloon.findViewById(R.id.text);
textmsg.setText("I am a Popup Balloon!!!");
mapView.addView(noteBaloon, new MapView.LayoutParams(200,200, new OverlayItem(new GeoPoint((int)(tX),(int)(tY)), "Seven Lagoon", "Seven Lagoon").getPoint(),MapView.LayoutParams.BOTTOM_CENTER));
mapView.setEnabled(false);
locations.add(new OverlayItem(new GeoPoint((int)(tX),(int)(tY)), "Seven Lagoon", "Seven Lagoon"));
populate();
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
protected OverlayItem createItem(int i) {
return locations.get(i);
}
#Override
public int size() {
return locations.size();
}
}
}
android-mapviewballoons library provides an easy way to annotate map overlay items with a simple information balloon when using Google Maps. Create a subclass of
BalloonItemizedOverlay
in the same way you would do for the base
ItemizedOverlay
class.
Here is a sample output
Can I parse kml file in order to display paths or points in Android? Please could you help me with that?
This is kml sample code which I would like to display in android google map:
<?xml version="1.0" encoding="UTF-8"?>
<kml xmlns="http://www.opengis.net/kml/2.2">
<Document>
<name>Paths</name>
<description>Examples of paths. Note that the tessellate tag is by default
set to 0. If you want to create tessellated lines, they must be authored
(or edited) directly in KML.</description>
<Style id="yellowLineGreenPoly">
<LineStyle>
<color>7f00ffff</color>
<width>4</width>
</LineStyle>
<PolyStyle>
<color>7f00ff00</color>
</PolyStyle>
</Style>
<Placemark>
<name>Absolute Extruded</name>
<description>Transparent green wall with yellow outlines</description>
<styleUrl>#yellowLineGreenPoly</styleUrl>
<LineString>
<extrude>1</extrude>
<tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode>
<coordinates> -112.2550785337791,36.07954952145647,2357
-112.2549277039738,36.08117083492122,2357
-112.2552505069063,36.08260761307279,2357
-112.2564540158376,36.08395660588506,2357
-112.2580238976449,36.08511401044813,2357
-112.2595218489022,36.08584355239394,2357
-112.2608216347552,36.08612634548589,2357
-112.262073428656,36.08626019085147,2357
-112.2633204928495,36.08621519860091,2357
-112.2644963846444,36.08627897945274,2357
-112.2656969554589,36.08649599090644,2357
</coordinates>
<LineString>
</Placemark>
</Document>
</kml>
When I'm loading this file to standard web google map it displays it nicely but when I'm trying the same thing with android google map it doesn't do that. It just takes me to some locations and that's it. I was thinking of changing listener class. Currently it looks like that:
private class MyLocationListener implements LocationListener
{
#Override
public void onLocationChanged(Location loc) {
if (loc != null) {
latitude = (loc.getLatitude() * 1E6);
longitude = (loc.getLongitude() * 1E6);
Toast.makeText(getBaseContext(),
"Location changed : Lat: " + latitude +
" Lng: " + longitude,
Toast.LENGTH_SHORT).show();
GeoPoint p = new GeoPoint(
(int) (loc.getLatitude() * 1E6),
(int) (loc.getLongitude() * 1E6));
mc.animateTo(p);
mapView.invalidate();
}
}
//---------------------------------------------------------------
#Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String provider, int status,
Bundle extras) {
//TODO Auto-generated method stub
}
Please can someone tell me what's I'm doing wrong here?
In above code, you don't pass the kml data to your mapView anywhere in your code, as far as I can see.
To display the route, you should parse the kml data i.e. via SAX parser, then display the route markers on the map.
See the code below for an example, but it's not complete though - just for you as a reference and get some idea.
This is a simple bean I use to hold the route information I will be parsing.
package com.myapp.android.model.navigation;
import java.util.ArrayList;
import java.util.Iterator;
public class NavigationDataSet {
private ArrayList<Placemark> placemarks = new ArrayList<Placemark>();
private Placemark currentPlacemark;
private Placemark routePlacemark;
public String toString() {
String s= "";
for (Iterator<Placemark> iter=placemarks.iterator();iter.hasNext();) {
Placemark p = (Placemark)iter.next();
s += p.getTitle() + "\n" + p.getDescription() + "\n\n";
}
return s;
}
public void addCurrentPlacemark() {
placemarks.add(currentPlacemark);
}
public ArrayList<Placemark> getPlacemarks() {
return placemarks;
}
public void setPlacemarks(ArrayList<Placemark> placemarks) {
this.placemarks = placemarks;
}
public Placemark getCurrentPlacemark() {
return currentPlacemark;
}
public void setCurrentPlacemark(Placemark currentPlacemark) {
this.currentPlacemark = currentPlacemark;
}
public Placemark getRoutePlacemark() {
return routePlacemark;
}
public void setRoutePlacemark(Placemark routePlacemark) {
this.routePlacemark = routePlacemark;
}
}
And the SAX Handler to parse the kml:
package com.myapp.android.model.navigation;
import android.util.Log;
import com.myapp.android.myapp;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import com.myapp.android.model.navigation.NavigationDataSet;
import com.myapp.android.model.navigation.Placemark;
public class NavigationSaxHandler extends DefaultHandler{
// ===========================================================
// Fields
// ===========================================================
private boolean in_kmltag = false;
private boolean in_placemarktag = false;
private boolean in_nametag = false;
private boolean in_descriptiontag = false;
private boolean in_geometrycollectiontag = false;
private boolean in_linestringtag = false;
private boolean in_pointtag = false;
private boolean in_coordinatestag = false;
private StringBuffer buffer;
private NavigationDataSet navigationDataSet = new NavigationDataSet();
// ===========================================================
// Getter & Setter
// ===========================================================
public NavigationDataSet getParsedData() {
navigationDataSet.getCurrentPlacemark().setCoordinates(buffer.toString().trim());
return this.navigationDataSet;
}
// ===========================================================
// Methods
// ===========================================================
#Override
public void startDocument() throws SAXException {
this.navigationDataSet = new NavigationDataSet();
}
#Override
public void endDocument() throws SAXException {
// Nothing to do
}
/** Gets be called on opening tags like:
* <tag>
* Can provide attribute(s), when xml was like:
* <tag attribute="attributeValue">*/
#Override
public void startElement(String namespaceURI, String localName,
String qName, Attributes atts) throws SAXException {
if (localName.equals("kml")) {
this.in_kmltag = true;
} else if (localName.equals("Placemark")) {
this.in_placemarktag = true;
navigationDataSet.setCurrentPlacemark(new Placemark());
} else if (localName.equals("name")) {
this.in_nametag = true;
} else if (localName.equals("description")) {
this.in_descriptiontag = true;
} else if (localName.equals("GeometryCollection")) {
this.in_geometrycollectiontag = true;
} else if (localName.equals("LineString")) {
this.in_linestringtag = true;
} else if (localName.equals("point")) {
this.in_pointtag = true;
} else if (localName.equals("coordinates")) {
buffer = new StringBuffer();
this.in_coordinatestag = true;
}
}
/** Gets be called on closing tags like:
* </tag> */
#Override
public void endElement(String namespaceURI, String localName, String qName)
throws SAXException {
if (localName.equals("kml")) {
this.in_kmltag = false;
} else if (localName.equals("Placemark")) {
this.in_placemarktag = false;
if ("Route".equals(navigationDataSet.getCurrentPlacemark().getTitle()))
navigationDataSet.setRoutePlacemark(navigationDataSet.getCurrentPlacemark());
else navigationDataSet.addCurrentPlacemark();
} else if (localName.equals("name")) {
this.in_nametag = false;
} else if (localName.equals("description")) {
this.in_descriptiontag = false;
} else if (localName.equals("GeometryCollection")) {
this.in_geometrycollectiontag = false;
} else if (localName.equals("LineString")) {
this.in_linestringtag = false;
} else if (localName.equals("point")) {
this.in_pointtag = false;
} else if (localName.equals("coordinates")) {
this.in_coordinatestag = false;
}
}
/** Gets be called on the following structure:
* <tag>characters</tag> */
#Override
public void characters(char ch[], int start, int length) {
if(this.in_nametag){
if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
navigationDataSet.getCurrentPlacemark().setTitle(new String(ch, start, length));
} else
if(this.in_descriptiontag){
if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
navigationDataSet.getCurrentPlacemark().setDescription(new String(ch, start, length));
} else
if(this.in_coordinatestag){
if (navigationDataSet.getCurrentPlacemark()==null) navigationDataSet.setCurrentPlacemark(new Placemark());
//navigationDataSet.getCurrentPlacemark().setCoordinates(new String(ch, start, length));
buffer.append(ch, start, length);
}
}
}
and a simple placeMark bean:
package com.myapp.android.model.navigation;
public class Placemark {
String title;
String description;
String coordinates;
String address;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getCoordinates() {
return coordinates;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
}
Finally the service class in my model that calls the calculation:
package com.myapp.android.model.navigation;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import com.myapp.android.myapp;
import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;
import android.util.Log;
public class MapService {
public static final int MODE_ANY = 0;
public static final int MODE_CAR = 1;
public static final int MODE_WALKING = 2;
public static String inputStreamToString (InputStream in) throws IOException {
StringBuffer out = new StringBuffer();
byte[] b = new byte[4096];
for (int n; (n = in.read(b)) != -1;) {
out.append(new String(b, 0, n));
}
return out.toString();
}
public static NavigationDataSet calculateRoute(Double startLat, Double startLng, Double targetLat, Double targetLng, int mode) {
return calculateRoute(startLat + "," + startLng, targetLat + "," + targetLng, mode);
}
public static NavigationDataSet calculateRoute(String startCoords, String targetCoords, int mode) {
String urlPedestrianMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
+ targetCoords + "&sll=" + startCoords + "&dirflg=w&hl=en&ie=UTF8&z=14&output=kml";
Log.d(myapp.APP, "urlPedestrianMode: "+urlPedestrianMode);
String urlCarMode = "http://maps.google.com/maps?" + "saddr=" + startCoords + "&daddr="
+ targetCoords + "&sll=" + startCoords + "&hl=en&ie=UTF8&z=14&output=kml";
Log.d(myapp.APP, "urlCarMode: "+urlCarMode);
NavigationDataSet navSet = null;
// for mode_any: try pedestrian route calculation first, if it fails, fall back to car route
if (mode==MODE_ANY||mode==MODE_WALKING) navSet = MapService.getNavigationDataSet(urlPedestrianMode);
if (mode==MODE_ANY&&navSet==null||mode==MODE_CAR) navSet = MapService.getNavigationDataSet(urlCarMode);
return navSet;
}
/**
* Retrieve navigation data set from either remote URL or String
* #param url
* #return navigation set
*/
public static NavigationDataSet getNavigationDataSet(String url) {
// urlString = "http://192.168.1.100:80/test.kml";
Log.d(myapp.APP,"urlString -->> " + url);
NavigationDataSet navigationDataSet = null;
try
{
final URL aUrl = new URL(url);
final URLConnection conn = aUrl.openConnection();
conn.setReadTimeout(15 * 1000); // timeout for reading the google maps data: 15 secs
conn.connect();
/* Get a SAXParser from the SAXPArserFactory. */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
/* Get the XMLReader of the SAXParser we created. */
XMLReader xr = sp.getXMLReader();
/* Create a new ContentHandler and apply it to the XML-Reader*/
NavigationSaxHandler navSax2Handler = new NavigationSaxHandler();
xr.setContentHandler(navSax2Handler);
/* Parse the xml-data from our URL. */
xr.parse(new InputSource(aUrl.openStream()));
/* Our NavigationSaxHandler now provides the parsed data to us. */
navigationDataSet = navSax2Handler.getParsedData();
/* Set the result to be displayed in our GUI. */
Log.d(myapp.APP,"navigationDataSet: "+navigationDataSet.toString());
} catch (Exception e) {
// Log.e(myapp.APP, "error with kml xml", e);
navigationDataSet = null;
}
return navigationDataSet;
}
}
Drawing:
/**
* Does the actual drawing of the route, based on the geo points provided in the nav set
*
* #param navSet Navigation set bean that holds the route information, incl. geo pos
* #param color Color in which to draw the lines
* #param mMapView01 Map view to draw onto
*/
public void drawPath(NavigationDataSet navSet, int color, MapView mMapView01) {
Log.d(myapp.APP, "map color before: " + color);
// color correction for dining, make it darker
if (color == Color.parseColor("#add331")) color = Color.parseColor("#6C8715");
Log.d(myapp.APP, "map color after: " + color);
Collection overlaysToAddAgain = new ArrayList();
for (Iterator iter = mMapView01.getOverlays().iterator(); iter.hasNext();) {
Object o = iter.next();
Log.d(myapp.APP, "overlay type: " + o.getClass().getName());
if (!RouteOverlay.class.getName().equals(o.getClass().getName())) {
// mMapView01.getOverlays().remove(o);
overlaysToAddAgain.add(o);
}
}
mMapView01.getOverlays().clear();
mMapView01.getOverlays().addAll(overlaysToAddAgain);
String path = navSet.getRoutePlacemark().getCoordinates();
Log.d(myapp.APP, "path=" + path);
if (path != null && path.trim().length() > 0) {
String[] pairs = path.trim().split(" ");
Log.d(myapp.APP, "pairs.length=" + pairs.length);
String[] lngLat = pairs[0].split(","); // lngLat[0]=longitude lngLat[1]=latitude lngLat[2]=height
Log.d(myapp.APP, "lnglat =" + lngLat + ", length: " + lngLat.length);
if (lngLat.length<3) lngLat = pairs[1].split(","); // if first pair is not transferred completely, take seconds pair //TODO
try {
GeoPoint startGP = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
mMapView01.getOverlays().add(new RouteOverlay(startGP, startGP, 1));
GeoPoint gp1;
GeoPoint gp2 = startGP;
for (int i = 1; i < pairs.length; i++) // the last one would be crash
{
lngLat = pairs[i].split(",");
gp1 = gp2;
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
// for GeoPoint, first:latitude, second:longitude
gp2 = new GeoPoint((int) (Double.parseDouble(lngLat[1]) * 1E6), (int) (Double.parseDouble(lngLat[0]) * 1E6));
if (gp2.getLatitudeE6() != 22200000) {
mMapView01.getOverlays().add(new RouteOverlay(gp1, gp2, 2, color));
Log.d(myapp.APP, "draw:" + gp1.getLatitudeE6() + "/" + gp1.getLongitudeE6() + " TO " + gp2.getLatitudeE6() + "/" + gp2.getLongitudeE6());
}
}
// Log.d(myapp.APP,"pair:" + pairs[i]);
}
//routeOverlays.add(new RouteOverlay(gp2,gp2, 3));
mMapView01.getOverlays().add(new RouteOverlay(gp2, gp2, 3));
} catch (NumberFormatException e) {
Log.e(myapp.APP, "Cannot draw route.", e);
}
}
// mMapView01.getOverlays().addAll(routeOverlays); // use the default color
mMapView01.setEnabled(true);
}
This is the RouteOverlay class:
package com.myapp.android.activity.map.nav;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.graphics.RectF;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.Projection;
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mRadius=6;
private int mode=0;
private int defaultColor;
private String text="";
private Bitmap img = null;
public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode) { // GeoPoint is a int. (6E)
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
defaultColor = 999; // no defaultColor
}
public RouteOverlay(GeoPoint gp1,GeoPoint gp2,int mode, int defaultColor) {
this.gp1 = gp1;
this.gp2 = gp2;
this.mode = mode;
this.defaultColor = defaultColor;
}
public void setText(String t) {
this.text = t;
}
public void setBitmap(Bitmap bitmap) {
this.img = bitmap;
}
public int getMode() {
return mode;
}
#Override
public boolean draw (Canvas canvas, MapView mapView, boolean shadow, long when) {
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
// mode=1:start
if(mode==1) {
if(defaultColor==999)
paint.setColor(Color.BLACK); // Color.BLUE
else
paint.setColor(defaultColor);
RectF oval=new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
// start point
canvas.drawOval(oval, paint);
}
// mode=2:path
else if(mode==2) {
if(defaultColor==999)
paint.setColor(Color.RED);
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
}
/* mode=3:end */
else if(mode==3) {
/* the last path */
if(defaultColor==999)
paint.setColor(Color.BLACK); // Color.GREEN
else
paint.setColor(defaultColor);
Point point2 = new Point();
projection.toPixels(gp2, point2);
paint.setStrokeWidth(5);
paint.setAlpha(defaultColor==Color.parseColor("#6C8715")?220:120);
canvas.drawLine(point.x, point.y, point2.x,point2.y, paint);
RectF oval=new RectF(point2.x - mRadius,point2.y - mRadius,
point2.x + mRadius,point2.y + mRadius);
/* end point */
paint.setAlpha(255);
canvas.drawOval(oval, paint);
}
}
return super.draw(canvas, mapView, shadow, when);
}
}
Thank Mathias Lin, tested and it works!
In addition, sample implementation of Mathias's method in activity can be as follows.
public class DirectionMapActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.directionmap);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
// Acquire a reference to the system Location Manager
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
String locationProvider = LocationManager.NETWORK_PROVIDER;
Location lastKnownLocation = locationManager.getLastKnownLocation(locationProvider);
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.google.com/maps?f=d&hl=en");
urlString.append("&saddr=");//from
urlString.append( Double.toString(lastKnownLocation.getLatitude() ));
urlString.append(",");
urlString.append( Double.toString(lastKnownLocation.getLongitude() ));
urlString.append("&daddr=");//to
urlString.append( Double.toString((double)dest[0]/1.0E6 ));
urlString.append(",");
urlString.append( Double.toString((double)dest[1]/1.0E6 ));
urlString.append("&ie=UTF8&0&om=0&output=kml");
try{
// setup the url
URL url = new URL(urlString.toString());
// create the factory
SAXParserFactory factory = SAXParserFactory.newInstance();
// create a parser
SAXParser parser = factory.newSAXParser();
// create the reader (scanner)
XMLReader xmlreader = parser.getXMLReader();
// instantiate our handler
NavigationSaxHandler navSaxHandler = new NavigationSaxHandler();
// assign our handler
xmlreader.setContentHandler(navSaxHandler);
// get our data via the url class
InputSource is = new InputSource(url.openStream());
// perform the synchronous parse
xmlreader.parse(is);
// get the results - should be a fully populated RSSFeed instance, or null on error
NavigationDataSet ds = navSaxHandler.getParsedData();
// draw path
drawPath(ds, Color.parseColor("#add331"), mapView );
// find boundary by using itemized overlay
GeoPoint destPoint = new GeoPoint(dest[0],dest[1]);
GeoPoint currentPoint = new GeoPoint( new Double(lastKnownLocation.getLatitude()*1E6).intValue()
,new Double(lastKnownLocation.getLongitude()*1E6).intValue() );
Drawable dot = this.getResources().getDrawable(R.drawable.pixel);
MapItemizedOverlay bgItemizedOverlay = new MapItemizedOverlay(dot,this);
OverlayItem currentPixel = new OverlayItem(destPoint, null, null );
OverlayItem destPixel = new OverlayItem(currentPoint, null, null );
bgItemizedOverlay.addOverlay(currentPixel);
bgItemizedOverlay.addOverlay(destPixel);
// center and zoom in the map
MapController mc = mapView.getController();
mc.zoomToSpan(bgItemizedOverlay.getLatSpanE6()*2,bgItemizedOverlay.getLonSpanE6()*2);
mc.animateTo(new GeoPoint(
(currentPoint.getLatitudeE6() + destPoint.getLatitudeE6()) / 2
, (currentPoint.getLongitudeE6() + destPoint.getLongitudeE6()) / 2));
} catch(Exception e) {
Log.d("DirectionMap","Exception parsing kml.");
}
}
// and the rest of the methods in activity, e.g. drawPath() etc...
MapItemizedOverlay.java
public class MapItemizedOverlay extends ItemizedOverlay{
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public MapItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
}
There is now a beta available of Google Maps KML Importing Utility.
It is part of the Google Maps Android API Utility Library. As documented it allows loading KML files from streams
KmlLayer layer = new KmlLayer(getMap(), kmlInputStream, getApplicationContext());
or local resources
KmlLayer layer = new KmlLayer(getMap(), R.raw.kmlFile, getApplicationContext());
After you have created a KmlLayer, call addLayerToMap() to add the imported data onto the map.
layer.addLayerToMap();
Mathias Lin code working beautifully. However, you might want to consider changing this part inside drawPath method:
if (lngLat.length >= 2 && gp1.getLatitudeE6() > 0 && gp1.getLongitudeE6() > 0
&& gp2.getLatitudeE6() > 0 && gp2.getLongitudeE6() > 0) {
GeoPoint can be less than zero as well, I switch mine to:
if (lngLat.length >= 2 && gp1.getLatitudeE6() != 0 && gp1.getLongitudeE6() != 0
&& gp2.getLatitudeE6() != 0 && gp2.getLongitudeE6() != 0) {
Thank you :D