Mark name of location on map? - android

In my Android app I want to mark on map a location (I know the address of location). When I mark it on map, I want to display the name of location,too. How can I do that?
I have this: OverlayItem(p ,"Kaufland", "Magic Kingdom"),but on map appear only the point,without the name.
Here is my code:
package com.ShoppingList.Shops;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import com.ShoppingList.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import java.util.ArrayList;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class ShowMap extends MapActivity {
private MapView mapView;
MapController mc;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.showmap);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
mapView.setClickable(true);
Drawable marker=getResources().getDrawable(R.drawable.pushpin);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
InterestingLocations funPlaces = new InterestingLocations(marker);
mapView.getOverlays().add(funPlaces);
GeoPoint pt = funPlaces.getCenter(); // get the first-ranked point
mapView.getController().setCenter(pt);
mapView.getController().setZoom(15);
}
#Override
protected boolean isLocationDisplayed() {
return false;
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class InterestingLocations extends ItemizedOverlay {
private List locations = new ArrayList();
private Drawable marker;
String adresa;
public InterestingLocations(Drawable marker)
{
super(marker);
this.marker=marker;
// create locations of interest
Bundle bundle = getIntent().getExtras();
adresa = bundle.getString("adress");
Geocoder geoCoder = new Geocoder(ShowMap.this, Locale.getDefault());
try {
List addresses = geoCoder.getFromLocationName(adresa, 5);
String add = "";
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6),
(int) (addresses.get(0).getLongitude() * 1E6));
locations.add(new OverlayItem(p ,"Kaufland", "Magic Kingdom"));
}
} catch (IOException e) {
e.printStackTrace();
}
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();
}
}
}

I can't believe there's no easier way but it doesn't look like there is. Here is one method:
http://binwaheed.blogspot.com/2011/05/android-display-title-on-marker-in.html
Also I highly recommend using anti-aliasing unless you want ugly text:
TextPaint paintText = new TextPaint(Paint.ANTI_ALIAS_FLAG);

I used a Toast to display the text indicated by the marker. Here's how I solved it for a demo project:
-- begin Location.java --
package com.cb2enterprises.geocode;
import com.google.android.maps.GeoPoint;
public class Location
{
public GeoPoint Point;
public String Title;
public String Snippet;
public Location(GeoPoint point, String title, String snippet)
{
Point = point;
Title = title;
Snippet = snippet;
}
}
-- end --
-- begin PushpinOverlay.java --
package com.cb2enterprises.geocode;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import android.view.Gravity;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
import java.util.ArrayList;
import java.util.List;
public class PushpinOverlay extends ItemizedOverlay<OverlayItem>
{
private List<Location> mItems;
Context mContext = null;
public PushpinOverlay(Context context, Drawable marker)
{
super(boundCenterBottom(marker));
mContext = context;
}
public void setItems(ArrayList<Location> items)
{
mItems = items;
populate();
}
#Override
protected OverlayItem createItem(int i)
{
return new OverlayItem(mItems.get(i).Point, mItems.get(i).Title, mItems.get(i).Snippet);
}
#Override
public int size() {
return mItems.size();
}
#Override
protected boolean onTap(int i)
{
Toast msg = Toast.makeText(mContext, mItems.get(i).Title, Toast.LENGTH_LONG);
msg.setGravity(Gravity.CENTER, msg.getXOffset() / 2, msg.getYOffset() / 2);
msg.show();
return true;
}
}
-- end --
-- begin GeoCodeDemoActivity.java --
package com.cb2enterprises.geocode;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
public class GeoCodeDemoActivity extends MapActivity
{
Geocoder geocoder = null;
MapView mapView = null;
ProgressDialog progDialog = null;
List<Address> addressList = null;
MyLocationOverlay curLocOverlay = null;
ArrayList<Location> locations = null;
PushpinOverlay pushpin = null;
#Override
protected boolean isLocationDisplayed()
{
return false;
}
#Override
protected boolean isRouteDisplayed()
{
return false;
}
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapView = (MapView)findViewById(R.id.geoMap);
mapView.setBuiltInZoomControls(true);
locations = new ArrayList<Location>();
Drawable icon = getResources().getDrawable(R.drawable.pin);
pushpin = new PushpinOverlay(this, icon);
// put the current location as hockey puck
curLocOverlay = new MyLocationOverlay(this, mapView);
curLocOverlay.runOnFirstFix(new Runnable()
{
public void run()
{
mapView.getController().animateTo(curLocOverlay.getMyLocation());
}
});
mapView.getOverlays().add(curLocOverlay);
mapView.getController().setZoom(12);
Button geoBtn = (Button)findViewById(R.id.geocodeBtn);
geocoder = new Geocoder(this);
geoBtn.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
EditText loc = (EditText)findViewById(R.id.location);
String locationName = loc.getText().toString();
progDialog = ProgressDialog.show(GeoCodeDemoActivity.this, "Processing",
"Finding location", true, false);
findLocation(locationName);
}
});
}
#Override
public void onResume()
{
super.onResume();
curLocOverlay.enableMyLocation();
}
#Override
public void onPause()
{
super.onPause();
curLocOverlay.disableMyLocation();
}
private void findLocation(final String locationName)
{
Thread thrd = new Thread()
{
public void run()
{
try
{
//do background work
addressList = geocoder.getFromLocationName(locationName, 5);
//send message to handler to process results
uiCallback.sendEmptyMessage(0);
}
catch (IOException e)
{
e.printStackTrace();
}
}
};
thrd.start();
}
//ui thread callback handler
private Handler uiCallback = new Handler()
{
#Override
public void handleMessage(Message msg)
{
progDialog.dismiss();
if(addressList != null && addressList.size() > 0)
{
int lat = (int)(addressList.get(0).getLatitude()*1E6);
int lng = (int)(addressList.get(0).getLongitude()*1E6);
GeoPoint pt = new GeoPoint(lat, lng);
locations.add(new Location(pt, addressList.get(0).getFeatureName(), addressList.get(0).getAddressLine(0)));
pushpin.setItems(locations);
mapView.getOverlays().add(pushpin);
mapView.getController().setCenter(locations.get(locations.size()-1).Point);
mapView.getController().setZoom(15);
}
else
{
Dialog foundNothingDlg = new AlertDialog.Builder(GeoCodeDemoActivity.this)
.setIcon(0)
.setTitle("Failed to find location")
.setPositiveButton("Ok", null)
.setMessage("Location not found...")
.create();
foundNothingDlg.show();
}
}
};
}

Related

when pin touch then how to open map balloon (annotation) for more information in android

I make small static map application, in which i take three pin(marker) and set static longitude and latitude. Actually, i want to display balloon annotation for location information display in mapview. when i touch the marker(pin) then balloon annotation is open and display the information for current location. My code is following:
**Source Code: MainActivity.java
----------------------------------**
package com.example.mapapp;
import java.util.List;
import com.google.android.maps.*;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends MapActivity {
MapController mpc;
//Button hotels,theaters,bank;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
/* hotels = (Button)findViewById(R.id.btnhotels);
hotels.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i = new Intent(MainActivity.this,Hotels.class);
startActivity(i);
}
});
theaters = (Button)findViewById(R.id.btntheaters);
theaters.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i1 = new Intent(MainActivity.this,Theaters.class);
startActivity(i1);
}
});
bank = (Button)findViewById(R.id.btnbank);
bank.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent i2 = new Intent(MainActivity.this,Bank.class);
startActivity(i2);
}
});*/
MapView mp = (MapView)findViewById(R.id.mapview);
mp.setBuiltInZoomControls(true);
mp.setSatellite(true);
mp.setTraffic(true);
mp.setStreetView(true);
mpc = mp.getController();
//for RL WebSolutions
double rl_lat = Double.parseDouble("23.0355018");
double rl_lon = Double.parseDouble("72.5630625");
GeoPoint point = new GeoPoint((int)(rl_lat*1E6), (int)(rl_lon*1E6));
mpc.animateTo(point);
mpc.setZoom(15);
mp.invalidate();
List<Overlay> mapoverlays = mp.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.redpin);
AddItemizedOverlay itemizedOverlay = new AddItemizedOverlay(drawable,this);
OverlayItem overlayitem = new OverlayItem(point, "Rl Websolution", "Here is RL Websolutions");
itemizedOverlay.addOverlay(overlayitem);
mapoverlays.add(itemizedOverlay);
//for State Bank of India
double stb_lat = Double.parseDouble("23.066519");
double stb_lon = Double.parseDouble("72.56956000000002");
GeoPoint point1 = new GeoPoint((int)(stb_lat*1E6), (int)(stb_lon*1E6));
mpc.animateTo(point1);
mpc.setZoom(15);
mp.invalidate();
List<Overlay> mpoverlays = mp.getOverlays();
Drawable d = this.getResources().getDrawable(R.drawable.poin1);
AddItemizedOverlay itemizeOverlay = new AddItemizedOverlay(d,this);
OverlayItem over = new OverlayItem(point1, "State Bank Of India", "Here is State Bank");
itemizeOverlay.addOverlay(over);
mpoverlays.add(itemizeOverlay);
//for Navrangpura Bus Stop
double bus_lat = Double.parseDouble("23.035626");
double bus_lon = Double.parseDouble("72.5641536");
GeoPoint point2 = new GeoPoint((int)(bus_lat*1E6), (int)(bus_lon*1E6));
mpc.animateTo(point2);
mpc.setZoom(15);
mp.invalidate();
List<Overlay> mboverlays = mp.getOverlays();
Drawable d1 = this.getResources().getDrawable(R.drawable.bus);
AddItemizedOverlay itemizOverlay = new AddItemizedOverlay(d1,this);
OverlayItem over1 = new OverlayItem(point2, "Navrangpura Bus Stop", "Here is Bus Stop");
itemizOverlay.addOverlay(over1);
mboverlays.add(itemizOverlay);
}
protected boolean isRouteDisplayed() {
return true;
}
}
****Here AddItemizedOverlay.java**
-----------------------------------**
package com.example.mapapp;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.util.Log;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class AddItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public AddItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public AddItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return mapOverlays.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(context);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
mapOverlays.add(overlay);
this.populate();
}
}
I think this is the perfect example you are looking for:
http://wptrafficanalyzer.in/blog/adding-marker-on-touched-location-of-google-maps-using-android-api-v2-with-supportmapfragment/

Drag and Drop pin on google map manually and get Longitude & Latitude accordingly

In Google Maps, I'm dropping a pin on user's current location but now I want to give another functionality to user that he can drag that pin manually and drop anywhere on the map, also by the time he drops the pin manually I can receive a callback which gives me the Longitude and Latitude of that position where user drops that pin.
If you can give me some examples it will be greatly appreciable.
In the last few days I finally found how to implement those functions you described and because there was no answer in this question, I decided to post what I found even though there has been a long time since you asked and you may found another answer by yourself.
So, I used the code of this git. I managed to do all that you want except the callback that I didn't try it in that way. I am getting the position of the pin after pressing a button.
There is no need to post my AndroidManifest because I read that you had no problem with displaying your location, so the permissions needed were fine.
The only thing that was required to do, was to create an activity named MapsActivity.
This is the whole content of it:
import com.google.android.gms.maps.*;
import com.google.android.gms.maps.model.*;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageButton;
import android.widget.Toast;
import common.logger.Log;
public class MapsActivity extends Activity implements
OnMapReadyCallback, GoogleMap.OnInfoWindowClickListener,
GoogleMap.OnMarkerDragListener {
LatLng position = new LatLng(34.6767, 33.04455);
final Marker marker_final = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
MapFragment mapFragment = (MapFragment) getFragmentManager()
.findFragmentById(R.id.
map);
mapFragment.getMapAsync(this);
ImageButton returnback = (ImageButton)findViewById(R.id.returnback);
returnback.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(MapsActivity.this.getApplicationContext(), position.latitude + ":" + position.longitude, Toast.LENGTH_LONG).show();
}
});
}
#Override
public void onMapReady(GoogleMap map) {
map.setMyLocationEnabled(true);
map.moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13));
CameraUpdate zoom = CameraUpdateFactory.zoomTo(15);
map.animateCamera(zoom);
map.addMarker(new MarkerOptions()
.title("Shop")
.snippet("Is this the right location?")
.position(position))
.setDraggable(true);
// map.setInfoWindowAdapter(new PopupAdapter(getLayoutInflater()));
map.setOnInfoWindowClickListener(this);
map.setOnMarkerDragListener(this);
}
#Override
public void onInfoWindowClick(Marker marker) {
Toast.makeText(this, marker.getTitle(), Toast.LENGTH_LONG).show();
}
#Override
public void onMarkerDragStart(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Drag from %f:%f",
position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDrag(Marker marker) {
LatLng position0 = marker.getPosition();
Log.d(getClass().getSimpleName(),
String.format("Dragging to %f:%f", position0.latitude,
position0.longitude));
}
#Override
public void onMarkerDragEnd(Marker marker) {
position = marker.getPosition();
Log.d(getClass().getSimpleName(), String.format("Dragged to %f:%f",
position.latitude,
position.longitude));
}
}
This is my activity_maps.xml layout (I've also added an edit text, but there is no need to use it):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:descendantFocusability="beforeDescendants"
android:focusableInTouchMode="true"
android:background="#ecf0f1">
<ScrollView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="#+id/scrollView3" >
<LinearLayout
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:weightSum="1"
android:layout_height="wrap_content">
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="0.9"
android:id="#+id/locationsearch" />
<ImageButton
android:layout_width="40dp"
android:layout_height="40dp"
android:id="#+id/search"
android:layout_weight="0.1"
android:background="#drawable/search" />
</LinearLayout>
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="405dp"
android:name="com.google.android.gms.maps.MapFragment"/>
<ImageButton
android:layout_width="60dp"
android:layout_height="60dp"
android:id="#+id/returnback"
android:background="#drawable/less" />
</LinearLayout>
</ScrollView>
</LinearLayout>
Refer Below links where you can find samples from Commons guy
Sample
SO question
Hi Use the below code.
you will get the dropped pin position.
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;
public class rescue extends MapActivity {
private LocationManager myLocationManager;
private LocationListener myLocationListener;
private MapView myMapView;
private MapController myMapController;
private String provider;
private MyLocationOverlay me=null;
private int defaultLat =(int)(51.51216124955517);
private int defaultLong =(int)(-0.1373291015625);
private GeoPoint defaultGeoPint = new GeoPoint(defaultLat,defaultLong);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rescue);
setCurrentLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void setCurrentLocation()
{
myMapView = (MapView)findViewById(R.id.rescueMapView);
myMapView.setTraffic(true);
///myMapView.setBuiltInZoomControls(true);
myMapController = myMapView.getController();
myMapController.setZoom(16); //Fixed Zoom Level
myLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationListener = new MyLocationListener();
try
{
Criteria criteria = new Criteria();
provider = myLocationManager.getBestProvider(criteria, false);
Location location = myLocationManager.getLastKnownLocation(provider);
myLocationManager.requestLocationUpdates(
provider,
0,
0,
myLocationListener);
Location lastLocation = myLocationManager.getLastKnownLocation(provider);
if(lastLocation != null)
{
int lastLocLat =(int)(lastLocation.getLatitude()*1000000);
int lastLocLong =(int)(lastLocation.getLongitude()*1000000);
//Get the current location in start-up
GeoPoint initGeoPoint = new GeoPoint(lastLocLat,lastLocLong);
CenterLocatio(initGeoPoint);
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Disabled")
.setMessage("The location service on the device are disabled, your location is not able to be found, please call AXA uding the button below to be rescued")
.setCancelable(false)
.setPositiveButton("Drop pin", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//do things
CenterLocatio(defaultGeoPint);
}
});
builder.create().show();
}
}
catch (Exception e)
{
// TODO: handle exception
Context context = getApplicationContext();
String toasttext = e.getMessage();
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
private void CenterLocatio(GeoPoint centerGeoPoint)
{
myMapView.getOverlays().clear();
myMapController.animateTo(centerGeoPoint);
Drawable marker=getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(),
marker.getIntrinsicHeight());
int lat = centerGeoPoint.getLatitudeE6();
int lon = centerGeoPoint.getLongitudeE6();
double lat1 = centerGeoPoint.getLatitudeE6()/1E6;
double lon1 = centerGeoPoint.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat1);
passing.add(lon1);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
myMapView.getOverlays().add(new SitesOverlay(marker,lat, lon ));
me=new MyLocationOverlay(this, myMapView);
myMapView.getOverlays().add(me);
};
private class MyLocationListener implements LocationListener{
#Override
public void onLocationChanged(Location argLocation) {
// TODO Auto-generated method stub
GeoPoint myGeoPoint = new GeoPoint(
(int)(argLocation.getLatitude()*1000000),
(int)(argLocation.getLongitude()*1000000));
//CenterLocatio(myGeoPoint);
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider,
int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
private GeoPoint getPoint(int lat, int lon) {
return(new GeoPoint(lat, lon));
/*
return(new GeoPoint((int)(lat*1000000.0),
(int)(lon*1000000.0)));
*/
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items=new ArrayList<OverlayItem>();
private Drawable marker=null;
private OverlayItem inDrag=null;
private ImageView dragImage=null;
private int xDragImageOffset=0;
private int yDragImageOffset=0;
private int xDragTouchOffset=0;
private int yDragTouchOffset=0;
public SitesOverlay(Drawable marker, int lat, int longitude) {
super(marker);
this.marker=marker;
dragImage=(ImageView)findViewById(R.id.drag);
xDragImageOffset=dragImage.getDrawable().getIntrinsicWidth()/2;
yDragImageOffset=dragImage.getDrawable().getIntrinsicHeight();
items.add(new OverlayItem(getPoint(lat,
longitude),
"UN", "United Nations"));
/*
items.add(new OverlayItem(getPoint(40.76866299974387,
-73.98268461227417),
"Lincoln Center",
"Home of Jazz at Lincoln Center"));
*/
populate();
}
#Override
protected OverlayItem createItem(int i) {
return(items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView,
boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
public int size() {
return(items.size());
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView) {
final int action=event.getAction();
final int x=(int)event.getX();
final int y=(int)event.getY();
boolean result=false;
if (action==MotionEvent.ACTION_DOWN) {
for (OverlayItem item : items) {
Point p=new Point(0,0);
myMapView.getProjection().toPixels(item.getPoint(), p);
if (hitTest(item, marker, x-p.x, y-p.y)) {
result=true;
inDrag=item;
items.remove(inDrag);
populate();
xDragTouchOffset=0;
yDragTouchOffset=0;
setDragImagePosition(p.x, p.y);
dragImage.setVisibility(View.VISIBLE);
xDragTouchOffset=x-p.x;
yDragTouchOffset=y-p.y;
break;
}
}
}
else if (action==MotionEvent.ACTION_MOVE && inDrag!=null) {
setDragImagePosition(x, y);
result=true;
}
else if (action==MotionEvent.ACTION_UP && inDrag!=null) {
dragImage.setVisibility(View.GONE);
GeoPoint pt=myMapView.getProjection().fromPixels(x-xDragTouchOffset,
y-yDragTouchOffset);
String title = inDrag.getTitle();
OverlayItem toDrop=new OverlayItem(pt, title,
inDrag.getSnippet());
items.add(toDrop);
populate();
double lat = pt.getLatitudeE6()/1E6;
double lon = pt.getLongitudeE6()/1E6;
ArrayList<Double> passing = new ArrayList<Double>();
passing.add(lat);
passing.add(lon);
Context context = getApplicationContext();
ReverseGeocodeLookupTask task = new ReverseGeocodeLookupTask();
task.applicationContext = context;
task.activityContext = rescue.this;
task.execute(passing);
//CenterLocatio(pt);
inDrag=null;
result=true;
}
return(result || super.onTouchEvent(event, mapView));
}
private void setDragImagePosition(int x, int y) {
RelativeLayout.LayoutParams lp=
(RelativeLayout.LayoutParams)dragImage.getLayoutParams();
lp.setMargins(x-xDragImageOffset-xDragTouchOffset,
y-yDragImageOffset-yDragTouchOffset, 0, 0);
dragImage.setLayoutParams(lp);
}
}
public class ReverseGeocodeLookupTask extends AsyncTask <ArrayList<Double>, Void, String>
{
private ProgressDialog dialog;
protected Context applicationContext;
protected Context activityContext;
#Override
protected void onPreExecute()
{
this.dialog = ProgressDialog.show(activityContext, "Please wait",
"Requesting location", true);
}
protected String doInBackground(ArrayList<Double>... params)
{
String foundAddress = "";
String localityName = "";
ArrayList<Double> passed = params[0];
double lat = passed.get(0);
double lon = passed.get(1);
try
{
List<Address> addresses = new Geocoder(applicationContext,Locale.getDefault()).getFromLocation(lat,lon, 1);
if (addresses.size() > 0)
{
String addressLine = "";
for(Integer i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
{
if(!addressLine.equals(""))
{
addressLine+= ", ";
}
addressLine+= addresses.get(0).getAddressLine(i);
}
if(addressLine!="")
{
foundAddress+= addressLine;
}
}
}
catch (Exception e) {
// TODO: handle exception
}
finally
{
}
return foundAddress;
}
#Override
protected void onPostExecute(String result)
{
this.dialog.cancel();
showToast(result);
}
}
public void showToast(String message)
{
Context context = getApplicationContext();
String toasttext = message;
int duration = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context, toasttext, duration);
toast.show();
}
}
Use below permission in manifest file
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<uses-library android:name="com.google.android.maps" />
<activity
android:label="#string/app_name"
android:name=".DragAndDropPinActivity" >
</activity>
<activity
android:label="#string/app_name"
android:name=".rescue" >
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

How get direction between two point on google map in android?

I searched for two hours but only found draw Line, i want get direction as this form Click here! I have ten point and when i click the point i want to show direction from my location to the point.
My code look:
package de.vogella.android.locationapi.maps;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
public class ShowMapActivity extends MapActivity {
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay,itemizedoverlay_central;
private MyLocationOverlay myLocationOverlay;
private String nameOfOffice_AZ[];
private String addressOfOffice_AZ[];
private String phoneOfOffice_AZ[];
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
// Configure the Map
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
Projection projection = mapView.getProjection();
nameOfOffice_AZ= getResources().getStringArray(R.array.NamesOFObject_AZ);
addressOfOffice_AZ = getResources().getStringArray(R.array.AddressOfOffice_AZ);
phoneOfOffice_AZ = getResources().getStringArray(R.array.PhoneOfOffice_AZ);
mapController = mapView.getController();
mapController.setZoom(16); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(myLocationOverlay.getMyLocation());
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.office_icon);
Drawable drawable_central = this.getResources().getDrawable(R.drawable.central_office);
itemizedoverlay = new MyOverlays(this, drawable);
itemizedoverlay_central = new MyOverlays(this, drawable_central);
createMarker();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class GeoUpdateHandler implements LocationListener {
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
createMarker();
mapController.animateTo(point); // mapController.setCenter(point);
}
#Override
public void onProviderDisabled(String provider) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
private void createMarker() {
//CENTRAL OFFICE
GeoPoint p_central = new GeoPoint((int)(40.38292884084829 * 1e6),(int)(49.84223246574 * 1e6));
OverlayItem overlayitem = new OverlayItem(p_central, nameOfOffice_AZ[0] ,addressOfOffice_AZ[0]+"\n"+phoneOfOffice_AZ[0] );
itemizedoverlay_central.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay_central);
//END CENTRALL OFFICE
GeoPoint p = new GeoPoint((int)(40.376455916943236 * 1e6),(int)(49.84803676605224 * 1e6));
overlayitem = new OverlayItem(p, nameOfOffice_AZ[0] ,addressOfOffice_AZ[0]+"\n"+phoneOfOffice_AZ[0] );
itemizedoverlay.addOverlay(overlayitem);
mapView.getOverlays().add(itemizedoverlay);
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onPause();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}
and MyOverlays.java
package de.vogella.android.locationapi.maps;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.widget.Toast;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class MyOverlays extends ItemizedOverlay<OverlayItem> {
private static int maxNum = 5;
private OverlayItem overlays[] = new OverlayItem[maxNum];
private int index = 0;
private boolean full = false;
private Context mContext;
private OverlayItem previousoverlay;
public MyOverlays(Context context, Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
this.mContext = context;
}
private ArrayList< OverlayItem > mOverlays = new ArrayList< OverlayItem >();
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void name() {
}
#Override
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
#Override
public int size() {
return mOverlays.size();
}
#Override
protected boolean onTap(int i) {
//when you tap on the marker this will show the informations provided by you when you create in the
//main class the OverlayItem
OverlayItem item = mOverlays.get(i);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setInverseBackgroundForced(true);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.setCancelable(true);
dialog.setPositiveButton("Go To", new OkOnClickListener());
/// dialog.setNegativeButton("No, no", new CancelOnClickListener());
dialog.show();
// nese bax = new nese();
// bax.oldu(mContext);
return true;
}
private final class CancelOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(mContext, "You clicked yes", Toast.LENGTH_LONG)
.show();
}
}
private final class OkOnClickListener implements
DialogInterface.OnClickListener {
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(mContext, "You clicked no", Toast.LENGTH_LONG).show();
}
}
public class RoutePath extends MapActivity {
/** Called when the activity is first created. */
MapView mapView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
double src_lat = 25.04202; // the testing source
double src_long = 121.534761;
double dest_lat = 25.05202; // the testing destination
double dest_long = 121.554761;
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6),
(int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6),
(int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.GREEN, mapView);
mapView.getController().animateTo(srcGeoPoint);
mapView.getController().setZoom(15);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
private void DrawPath(GeoPoint src, GeoPoint dest, int color,
MapView mMapView01) {
// code in section 2.2
}
}
}
Less efforts on search..
Anyway look at Google Driving Directions - MapView overlayed Also The Google Directions API
and using intent
Intent intent = new Intent(android.content.Intent.ACTION_VIEW,
Uri.parse("http://maps.google.com/maps?saddr=xx.xx,xx.xx&daddr=xx.xx,xx.xx"));
startActivity(intent);
This blogpost can be a good startpoint: Android driving direction Route-Path
Worked fine for me.

Android MapView

Please help me out, I am working on a Project Xyz having the mapView with add multiple overlays and remove overlays as per userChoice.
To be more clear it filters the overlays as per user choice,,,,
Suppose showing favorite places, friends of a user...
PostLoginServiceHomeBean is my ArrayList with an ArrayList NearByFavoritePlacesList object
entry.getNearByFavoritePlacesList().get(i).getGpsLatitude()
.trim()
i.e by this i'm getting the multiple lat long form server...
The code runs f9 and add the multiple overlays to my map and shows name and address of repective place on overlay tap.But how could I remove the overlays form my map...
I am enclosing the code:Please find the code below:
Please help me out....
package com.gogozing.app;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import com.gogozing.service.LocateServices;
import com.gogozing.util.Data;
import com.gogozing.util.PostLoginServiceHomeBean;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class HomeMapActivity extends MapActivity {
private MapView myMapView;
private MapController myMapController;
private List<Overlay> mapOverlays;
private HomeMapItemizedOverlay itemizedOverlay;
private Context context;
private PostLoginServiceHomeBean entry;
private GeoPoint initGeoPoint;
private CheckBox peopleCheckBox, friendsCheckBox, favoritesCheckBox;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.home_map_layout);
context = this;
backButton = (Button) findViewById(R.id.HomeMapLeftBackButton);
eventsBtn = (Button) findViewById(R.id.EventsBtn);
profileBtn = (Button) findViewById(R.id.ProflieBtn);
homeBtn = (Button) findViewById(R.id.HomeBtn);
locateButton = (Button) findViewById(R.id.LocateBtn);
socializeButton = (Button) findViewById(R.id.SocializeBtn);
peopleCheckBox = (CheckBox) findViewById(R.id.HomeMapViewPeopleCheckBox);
favoritesCheckBox = (CheckBox) findViewById(R.id.HomeMapViewFavoritesCheckBox);
friendsCheckBox = (CheckBox) findViewById(R.id.HomeMapViewFriendsCheckBox);
homeBtn.setBackgroundResource(R.drawable.home_f);
myMapView = (MapView) findViewById(R.id.mapviewHome);
myMapView.setBuiltInZoomControls(true);
// Set satellite view
myMapController = myMapView.getController();
// Get the current location in start-up
try {
entry = Data.postLoginServiceHomeMain.get(0);
favoritesCheckBox
.setOnCheckedChangeListener(new OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
viewFavoritePlaces();
} else
removeFavoritePlaces();
}
});
} catch (Exception e) {
Log.e(Data.LOG, e.getMessage(), e);
}
}
void viewFavoritePlaces() {
for (int i = 0; i < entry.getNearByFavoritePlacesList().size(); i++) {
double latitude = Double.valueOf(
**entry.getNearByFavoritePlacesList().get(i).getGpsLatitude()
.trim()**).doubleValue();
double longitude = Double.valueOf(
entry.getNearByFavoritePlacesList().get(i)
.getGpsLongitude().trim()).doubleValue();
Log.v(Data.LOG1, " Latitude " + latitude + " Longitude "
+ longitude);
String name = entry.getNearByFavoritePlacesList().get(i)
.getMerchantName();
String address = entry.getNearByFavoritePlacesList().get(i)
.getAddress();
initGeoPoint = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
mapOverlays = myMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(
R.drawable.map_store_place);
itemizedOverlay = new HomeMapItemizedOverlay(drawable, this);
OverlayItem overlayItem = new OverlayItem(initGeoPoint, name,
address);
itemizedOverlay.addOverlay(overlayItem);
mapOverlays.add(itemizedOverlay);
myMapController.animateTo(initGeoPoint);
myMapController.setZoom(15);
}
}
void removeFavoritePlaces() {
//List<Overlay> mapOverlays = myMapView.getOverlays();
mapOverlays.remove(itemizedOverlay);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
};
public class HomeMapItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HomeMapItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
public void removeOverlay(OverlayItem overlay)
{
mOverlays.remove(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;
}
}
}
Here I am giving one solution what I am getting from your question... You need to add Lat Long into Overlay item which is coming from server and add it to itemized overlay, after that when ever you would like to remove any Itemizedoverlay with specific lat long you can check and remove from map overlay as well.

Timers and Maps Android

I'm having some troubles with displaying ItemizedOverlay(s) on a map.
Here I extracted a simplified example of what I need to do.
Here's my Map class:
import java.util.Timer;
import java.util.TimerTask;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.util.Log;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.OverlayItem;
public class Map extends MapActivity {
protected static final String TAG = "Map";
private int test = 0;
private TestItemized items = null;
private Timer timer = new Timer();
private MapView map = null;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.map = (MapView) this.findViewById(R.id.myMapView1);
this.map.setBuiltInZoomControls(true);
this.map.setSatellite(false);
this.map.setStreetView(true);
this.map.setClickable(true);
this.timer.scheduleAtFixedRate(new TimerTask(){
#Override
public void run() {
Log.d(TAG, "refeshing: "+ String.valueOf(test));
Drawable drawable = Map.this.getResources().getDrawable(R.drawable.androidmarker);
test++;
if (Map.this.items instanceof TestItemized && Map.this.map.getOverlays().contains(Map.this.items))
Map.this.map.getOverlays().remove(Map.this.items);
//some code might go here to retrieve new coordinates but this isn't a problem
Map.this.items = new TestItemized(drawable, Map.this);
double lat = 46.491734;
Log.d(TAG,"Latitude : "+ String.valueOf(lat));
double lng = 11.320365;
Log.d(TAG,"Longitude : "+ String.valueOf(lng));
OverlayItem item = new OverlayItem(new GeoPoint((int)(lat * 1E6), (int)(lng * 1E6)), String.valueOf(Map.this.test), "blah!");
Map.this.items.addOverlay(item);
Map.this.map.getOverlays().add(Map.this.items);
Log.d(TAG,"refreshing "+String.valueOf(test)+" is over");
}}, 1000,60000);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
}
I followed the guide provided by google to extends the ItemizedOverlay class
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.widget.Toast;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
#SuppressWarnings("rawtypes")
public class TestItemized extends ItemizedOverlay {
private Context mCtx;
private List<OverlayItem> mItems = new ArrayList<OverlayItem>();
public TestItemized(Drawable arg0) {
super(arg0);
}
/**
* #param defaultMarker
* #param mCtx
*/
public TestItemized(Drawable defaultMarker, Context mCtx) {
super(defaultMarker);
this.mCtx = mCtx;
}
public void addOverlay(OverlayItem overlay) {
this.mItems.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return this.mItems.get(i);
}
#Override
public int size() {
return mItems.size();
}
/* (non-Javadoc)
* #see com.google.android.maps.ItemizedOverlay#onTap(int)
*/
#Override
protected boolean onTap(int index) {
OverlayItem item = this.mItems.get(index);
Toast.makeText(this.mCtx, item.getTitle() +" : " +item.getSnippet(), Toast.LENGTH_LONG).show();
return true;
}
}
As it is clear from the code I need to update at fixed times a map UI with possibly new positions to do so I'm using a timer, but I think I might fall in some kind of thread issues I don't know how to handle, since when running a test I can see in the Log what happens but no marker is drawn on the map. Does anybody know how to solve this kind of problem?
At the end of the run() method, after you finish updating your MapView you should call
Map.this.map.postInvalidate();

Categories

Resources