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
Related
I'm coding an application using osmdroid to show a map and i would like to add a marker to it when user taps over map, actually i have been able to do this usin motion event but this adds a marker even when user is zooming in or out the map i don't want this.
This is the code i have to add the marker:
#Override
public boolean dispatchTouchEvent(MotionEvent ev) {
int actionType = ev.getAction();
switch (actionType) {
case MotionEvent.ACTION_DOWN:
Projection proj = myOpenMapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)ev.getX(), (int)ev.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
List<OverlayItem> anotherOverlayItemArray = new ArrayList<OverlayItem>();
ExtendedOverlayItem mapItem = new ExtendedOverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)), this);
mapItem.setMarker(this.getResources().getDrawable(R.drawable.marker));
anotherOverlayItemArray.add(mapItem);
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay
= new ItemizedIconOverlay<OverlayItem>(
this, anotherOverlayItemArray, null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
Toast toast = Toast.makeText(getApplicationContext(), "Longitude: "+ longitude +" Latitude: "+ latitude , Toast.LENGTH_LONG);
toast.show();
}
return super.dispatchTouchEvent(ev);
}
This is how i finally solved it:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
}else{
myOpenMapView.getOverlays().remove(anotherItemizedIconOverlay);
myOpenMapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
myOpenMapView.getOverlays().add(anotherItemizedIconOverlay);
}
dlgThread();
return true;
}
};
myOpenMapView.getOverlays().add(touchOverlay);
You should create an Overlay and override the onSingleTapConfirmed() method to get single-taps:
#Override
public boolean onSingleTapConfirmed(final MotionEvent event, final MapView mapView) {
// Handle single-tap here, then return true.
return true;
}
I have an application where I fetch longitude and latitude from my database and want to display it in a MapView. I am able to show the one stored most recently, but I think some array is needed in a for loop to add it in an overlay. I don't know how to implement it though.
Here is my buttonClick on which it will fetch lat/long and display it in a MapView:
buttonShowMarkers = (Button) findViewById(R.id.button_SHOW_MARKERS);
buttonShowMarkers.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
db = openOrCreateDatabase("LocationFetch.db", MODE_PRIVATE , null);
cursor = db.rawQuery("SELECT * FROM user" , null);
cursor.moveToFirst();
do {
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
showLatLon(latitude , longitude , dataNAME);
// ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
/* List<Overlay> ListOverlays = mapView.getOverlays();
* OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
* OverlayItem markerItem = new OverlayItem(new GeoPoint((int)(latitude *1E6), (int)(longitude *1E6)) , ""+dataNAME , ""+dataString);
* drawableOne = getResources().getDrawable(R.drawable.location_blue);
* helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
* helloItemizedOverlay.addOverlayItem(markerItem);
* mapView.getOverlays().add(helloItemizedOverlay);
* ListOverlays.add(myItemizedOverlay);*/
//for(int i = dataID ; )
} while (cursor.moveToNext());
/*String[] arrLat = new String[]{LATdata};
String[] arrLon = new String[]{LONdata};*/
//showLatLon(dataLAT , dataLON);
cursor.moveToNext();
} catch(SQLException e) {
e.printStackTrace();
} finally {
cursor.close();
}
db.close();
}
private void showLatLon(int latitude , int longitude , String nAMEdata) {
// GeoPoint point = new GeoPoint( (latitude) , (latitude) );
List<Overlay> ListOverlays = mapView.getOverlays();
//OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
OverlayItem markerItem = new OverlayItem(new GeoPoint(latitude,latitude ) , ""+nAMEdata , null);
drawableOne = getResources().getDrawable(R.drawable.location_blue);
helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
helloItemizedOverlay.addOverlayItem(markerItem);
mapView.getOverlays().add(helloItemizedOverlay);
ListOverlays.add(myItemizedOverlay);
}
});
You can try using this solution -
Create a class named LatLonPoint - this basically does the conversion from latlon to GeoPoint -
public class LatLonPoint extends GeoPoint {
public LatLonPoint(double latitude, double longitude) {
super((int) (latitude * 1E6), (int) (longitude * 1E6));
}
}
Create a Itemized Overlay -
public class HelloItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(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();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event, MapView mapView) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
}
return super.onKeyDown(keyCode, event, mapView);
}
}
Now in the main activity -
try {
db = openOrCreateDatabase("LocationFetch.db", MODE_PRIVATE , null);
cursor = db.rawQuery("SELECT * FROM user" , null);
cursor.moveToFirst();
do {
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
// Add the item here --
itemizedoverlay.addOverlay(new OverlayItem(new LatLonPoint(latitude, longitude), dataNAME, null));
//showLatLon(latitude , longitude , dataNAME);
// ArrayList<OverlayItem> items = new ArrayList<OverlayItem>();
/* List<Overlay> ListOverlays = mapView.getOverlays();
* OverlayItem[] markerItem = {new OverlayItem(new GeoPoint(latitude, longitude) , ""+dataNAME , ""+dataString)};
* OverlayItem markerItem = new OverlayItem(new GeoPoint((int)(latitude *1E6), (int)(longitude *1E6)) , ""+dataNAME , ""+dataString);
* drawableOne = getResources().getDrawable(R.drawable.location_blue);
* helloItemizedOverlay = new HelloItemizedOverlay(drawableOne);
* helloItemizedOverlay.addOverlayItem(markerItem);
* mapView.getOverlays().add(helloItemizedOverlay);
* ListOverlays.add(myItemizedOverlay);*/
//for(int i = dataID ; )
} while (cursor.moveToNext());
// Add all itemized overlay here
mapOverlays.add(itemizedoverlay);
/*String[] arrLat = new String[]{LATdata};
String[] arrLon = new String[]{LONdata};*/
//showLatLon(dataLAT , dataLON);
//cursor.moveToNext();
} catch(SQLException e) {
e.printStackTrace();
} finally {
cursor.close();
}
For the above block you have to initialize these two items beffore the do.. while -
List<Overlay> mapOverlays = mMapView.getOverlays();
and
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, this);
EDIT-- Adding iterating Cursor Part -
Drawable drawable = this.getResources().getDrawable(
R.drawable.ic_launcher);
List<Overlay> mapOverlays = mMapView.getOverlays();
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(
drawable, this);
while(cursor.moveToNext())
{
// get the values --
int dataID = cursor.getColumnIndex("id");
String dataString = cursor.getString(0);
Log.d("ID DATA FROM DATABASE---->" , dataString);
String dataNAME = cursor.getString(1).toString().trim();
Log.d("NAME DATA FROM DATABASE---->", dataNAME);
String dataLAT = cursor.getString(2).toString().trim();
Log.d("LAT DATA FROM DATABASE----->" , dataLAT);
int latitude = cursor.getColumnIndex("latitude");
String dataLON = cursor.getString(3).toString().trim();
Log.d("LON DATA FROM DATABASE----->" , dataLON);
int longitude = cursor.getColumnIndex("longitude");
// Assuming your logic for retrieving values is correct
// Add into the itemized Overlay here
itemizedoverlay.addOverlay(new OverlayItem(new LatLonPoint(latitude, longitude), dataNAME, null));
}
mapOverlays.add(itemizedoverlay);
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.
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);
}
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