I'm having problems with linking the ArrayList of OverlayItems I have created in my CustomPinpoint class to the Listview. Basically I'm trying to display the markers I added on the map in a small list. But with the code below, I get a NullPointerException error. I understand why(I think its because I create 2 seperate instances of 'custom' which don't refer to each other), but I don't understand how I can solve it...
Thank you in advance.
package com.lars.pinpoint;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
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.Overlay;
import com.google.android.maps.OverlayItem;
import com.lars.pinpoint.R;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TabHost;
import android.widget.TextView;
import android.widget.Toast;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabContentFactory;
public class Main extends MapActivity implements OnTabChangeListener{
/** Called when the activity is first created. */
private static final String LIST_TAB_TAG = "List";
private static final String MAP_TAB_TAG = "Map";
MapView map;
ListView listView;
TabHost tabHost;
long start;
long stop;
int x, y;
MyLocationOverlay compass;
MyLocationOverlay MyLoc;
MapController controller;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
CustomPinpoint custom;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tabHost = (TabHost) findViewById(android.R.id.tabhost);
tabHost.setup();
listView = (ListView) findViewById(R.id.list);
listView.setEmptyView((TextView) findViewById(R.id.empty));
d = getResources().getDrawable(R.drawable.ic_launcher);
CustomPinpoint custom = new CustomPinpoint(d,Main.this);
listView.setAdapter(new ArrayAdapter<OverlayItem>(this, android.R.layout.simple_list_item_1, custom.pinpoints));
listView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
GeoPoint geoPoint = ((OverlayItem) listView.getAdapter().getItem(position)).getPoint();
if(geoPoint != null) {
map.getController().animateTo(geoPoint);
tabHost.setCurrentTab(1);
}
}
});
map = (MapView) findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
map.postInvalidate();
Touch t = new Touch();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Main.this, map);
overlayList.add(compass);
controller = map.getController();
MyLoc = new MyLocationOverlay(Main.this, map);
overlayList.add(MyLoc);
map.postInvalidate();
MyLoc.runOnFirstFix(new Runnable() {
public void run() {
map.getController().animateTo(MyLoc.getMyLocation());
}
});
tabHost.addTab(tabHost.newTabSpec(LIST_TAB_TAG).setIndicator("List").setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return listView;
}
}));
tabHost.addTab(tabHost.newTabSpec(MAP_TAB_TAG).setIndicator("Map").setContent(new TabContentFactory() {
public View createTabContent(String arg0) {
return map;
}
}));
//HACK to get the list view to show up first,
// otherwise the mapview would be bleeding through and visible
tabHost.setCurrentTab(1);
tabHost.setCurrentTab(0);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
MyLoc.disableMyLocation();
finish();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
MyLoc.enableMyLocation();
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
class Touch extends Overlay {
public boolean onTouchEvent(MotionEvent e, MapView m) {
if (e.getAction() == MotionEvent.ACTION_DOWN) {
start = e.getEventTime();
x = (int) e.getX();
y = (int) e.getY();
touchedPoint = map.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP) {
stop = e.getEventTime();
}
if (stop - start > 1500) {
AlertDialog alert = new AlertDialog.Builder(Main.this).create();
alert.setTitle("Pick an option.");
alert.setButton(DialogInterface.BUTTON_POSITIVE,"Place a pinpoint.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "Pinpoint", "2nd String");
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton(DialogInterface.BUTTON_NEUTRAL,"Get address.",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// TODO Auto-generated method stub
Geocoder geocoder = new Geocoder(getBaseContext(), Locale.getDefault());
try{
List<Address> address = geocoder.getFromLocation(touchedPoint.getLatitudeE6() /1E6, touchedPoint.getLongitudeE6()/1E6, 1);
if (address.size() > 0){
String display = "";
for (int i = 0; i < address.get(0).getMaxAddressLineIndex(); i++){
display += address.get(0).getAddressLine(i) + "\n";
}
Toast t3 = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t3.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton(DialogInterface.BUTTON_NEGATIVE,"Toggle View", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if (map.isSatellite()){
map.setSatellite(false);
}else{
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
public void gpsCurrentLocation()
{
tabHost.setCurrentTab(1);
GeoPoint p = MyLoc.getMyLocation();
map.getController().animateTo(p);
}
// Menu XML file (menu.xml)
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.my_location:
Toast.makeText(Main.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
gpsCurrentLocation();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
}
}
Use custom = new CustomPinpoint(d,Main.this);
instead of
CustomPinpoint custom = new CustomPinpoint(d,Main.this);
Related
I want to make multiple polyline in map. i have one polyline in maps, then i want to make new polyline again. but the line is always connect with previous polyline. what should i do, this is my code:
package com.evy;
import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapLongClickListener;
import com.google.android.gms.maps.GoogleMap.OnMarkerDragListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class Tambah extends FragmentActivity implements LocationListener{
GoogleMap map;
LocationManager lm;
boolean isNewPoly=false;
PolylineOptions polyline;
ArrayList<LatLng> poly = new ArrayList<LatLng>();
ArrayList<LatLng> points = new ArrayList<LatLng>();
PolylineOptions polylineOptions;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.tambah);
//points=new ArrayList<LatLng>();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.maptambah);
map=mapFragment.getMap();
final LocationListener ll=new LocationListener(){
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
map.addMarker(new MarkerOptions().position(new LatLng(location.getLatitude(),location.getLongitude())).title("posisi anda").icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(location.getLatitude(),location.getLongitude()), 15.0f));
}
#Override
public void onProviderDisabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProviderEnabled(String arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
// TODO Auto-generated method stub
}
};
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, ll);
Button stop = (Button) findViewById(R.id.stop);
Button start = (Button) findViewById(R.id.start);
map.setOnMapClickListener(new OnMapClickListener(){
#Override
public void onMapClick(LatLng point) {
// TODO Auto-generated method stub
if(isNewPoly==true){
MarkerOptions markerOptions = new MarkerOptions().position(point).title("Position").snippet("Latitude: "+point.latitude+" , "+"Longitude: "+point.longitude).icon(BitmapDescriptorFactory.fromResource(R.drawable.marker));
map.addMarker(markerOptions);
polylineOptions = new PolylineOptions().color(Color.BLUE).width(3);
points.add(point);
for(int i=0;i<points.size();i++){
polylineOptions.add(points.get(i));
}
map.addPolyline(polylineOptions);
}
for(int i=0;i<points.size();i++){
poly.add(points.get(i));
}
}
});
start.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
isNewPoly=true;
}
});
stop.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
isNewPoly=false;
}
});
}
public static String encode(final List<LatLng> path){
long lastLat = 0;
long lastLng = 0;
final StringBuffer result = new StringBuffer();
for(final LatLng point:path){
long lat = Math.round(point.latitude * 1e5);
long lng = Math.round(point.longitude * 1e5);
long dlat = lat - lastLat;
long dlng = lng - lastLng;
encoded(dlat, result);
encoded(dlng, result);
lastLat = lat;
lastLng = lng;
}
return result.toString();
}
private static void encoded(long v, StringBuffer result){
v = v < 0 ? ~(v<<1) : v<<1;
while(v >= 0x20){
result.append(Character.toChars((int) ((0x20 | (v & 0x1f))+63)));
v >>= 5;
}
result.append(Character.toChars((int) (v + 63)));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tambah, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
switch(item.getItemId()){
case R.id.home:
this.finish();
startActivity(new Intent(Tambah.this, Peta.class));
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
}
#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
}
}
if I press button start, it make new polyline, and press button stop to stop it, but it's not work. the button stop not warking.
You are currently append all points at once, instead you should use a PolyLine array. Assuming that coordinates1 and coordinates2 are the LatLng[] type of arrays that is previously appended from KML file or some other source. You should write something like below;
int size=3 //determine the size of array.
Polyline[] polyLine;
polyLine = new Polyline[size];
int i =0;
while (i<size)
{
polyLine[i] = map.addPolyline(new PolylineOptions()
.clickable(true)
.add(coordinates1[i],coordinates1[i+1]));
i++;
}
List<LatLng> latLngList = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
latLngList.add(i, new LatLng(arrayList.get(i).getLocation_lat(), arrayList.get(i).getLocation_lang()));
}
Polyline polyline = googleMaps.addPolyline(new PolylineOptions()
.clickable(true)
.addAll(latLngList)
.width(2).color(Color.BLUE).geodesic(true));
List<LatLng> latLngList = new ArrayList<>();
for (int i = 0; i < arrayList.size(); i++) {
latLngList.add(i, new LatLng(arrayList.get(i).getLocation_lat(), arrayList.get(i).getLocation_lang()));
}
Polyline polyline = mMap.addPolyline(new PolylineOptions()
.clickable(true)
.addAll(latLngList)
.width(2).color(Color.BLUE).geodesic(true));
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/
I am displaying the Google maps in the Android program.How can i save the places to Android Listview whenever I Click On One place in the map.
By this I am Getting the search place in the maps
package com.commonsware.android.nooer;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.DialogInterface.OnClickListener;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
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;
public class SampleMpas extends MapActivity {
MapView mapView;
MapController mapController;
GeoPoint mgeoPoint;
Drawable marker;
MyLocationOverlay mLocationOverlay;
MotionEvent e;
public void changeMap(String area)
{
MapController mc=mapView.getController();
GeoPoint myLocation=null;
double lat = 0;
double lng = 0;
try
{
Geocoder g = new Geocoder(this, Locale.getDefault());
java.util.List<android.location.Address> result=g.getFromLocationName(area, 1);
if(result.size()>0){
Toast.makeText(SampleMpas.this, "country: " + String.valueOf(result.get(0).getCountryName()), Toast.LENGTH_SHORT).show();
lat = result.get(0).getLatitude();
lng = result.get(0).getLongitude();
}
else{
Toast.makeText(SampleMpas.this, "record not found", Toast.LENGTH_SHORT).show();
return;
}
}
catch(IOException io)
{
Toast.makeText(SampleMpas.this, "Connection Error", Toast.LENGTH_SHORT).show();
}
myLocation = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
Drawable drawable = this.getResources().getDrawable(R.drawable.icon);
mc.animateTo(myLocation);
mc.setZoom(15);
mapView.invalidate();
}
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.main);
Button btnSearch=(Button) findViewById(R.id.btnSearch);
btnSearch.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
EditText txtSearch=(EditText)findViewById(R.id.txtMapSearch);
String area=txtSearch.getText().toString();
Toast.makeText(SampleMpas.this, "Click-" + String.valueOf(area), Toast.LENGTH_SHORT).show();
SampleMpas.this.changeMap(area);
}
});
mapView = (MapView) findViewById(R.id.map);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
marker = getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
.getIntrinsicHeight());
mapView.getOverlays().add(new MapOverlay(marker));
mLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mLocationOverlay);
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case 0:
return new AlertDialog.Builder(this).setTitle("Are You Want save this place As?").setIcon(
R.drawable.icon).setPositiveButton("Favorite",
new OnClickListener() {
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
}).setCancelable(true).setNegativeButton("Cancel",
new OnClickListener() {
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
}).setCancelable(true).setNeutralButton("Business", new OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
})
.setOnCancelListener(new OnCancelListener() {
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Dismiss",
Toast.LENGTH_SHORT).show();
}
}).create();
default:
break;
}
return null;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
Point scrPoint;
private GeoPoint getPoint(double lat , double lon) {
return (new GeoPoint((int) (lat * 1E6), (int) (lon * 1E6)));
}
class MapOverlay extends
com.google.android.maps.ItemizedOverlay<OverlayItem> {
List<OverlayItem> ListofGeopoints = new ArrayList<OverlayItem>();
public MapOverlay(Drawable defaultMarker ) {
super(defaultMarker);
double lat = 0;
double lang = 0;
ListofGeopoints.add(new OverlayItem(getPoint(lat, lang),
"IN", "India"));
populate();
}
#Override
protected boolean onTap(int index) {
switch (index) {
case 0:
Toast.makeText(getApplicationContext(), "GeoLocation : 0",
Toast.LENGTH_LONG).show();
showDialog(0);
break;
}
return true;
}
String add = "";
List<Address> add_List = new ArrayList<Address>();
private void getAddress() {
/* add_List = ReverseGeocode
.getFromLocation(35.594227, -105.223618, 2);
*/
}
#Override
protected OverlayItem createItem(int i) {
return (ListofGeopoints.get(i));
}
#Override
public int size() {
return ListofGeopoints.size();
}
}
}
Thanks in Advance.
You can get the geo points of the Touched location by
#Override
public boolean onTap(GeoPoint p , MapView mapView)
Write a class which derives from the Overlay class and override the onTap() method. Then you can add your overlay to the your MapView. A GeoPoint object, which represents the position of you tap, is passed to the onTap() method when you tab somewhere on the map. Save this Geo points in your DB and populate your list view from the database.
Sample Code: Overlay Class:
class MapOverlay extends
com.google.android.maps.ItemizedOverlay<OverlayItem> {
#Override
public boolean onTap(GeoPoint p , MapView mapView) {
// TODO Auto-generated method stub
Log.i("Latitude" , String.valueOf(p.getLatitudeE6()/1E6));
Log.i("Longitude", String.valueOf(p.getLongitudeE6()/1E6));
return super.onTap(p, mapView);
}
I have item list with latitude and longitude .I want to show the item list on Google map..
so, how to create overlay list and how to show overlays on Google map ?
This is what i did on my project...
package org.nip.gmap;
import java.util.List;
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.graphics.drawable.Drawable;
import android.os.Bundle;
public class Main extends MapActivity {
/** Called when the activity is first created. */
MapView map;
MapController controller;
List<Overlay> overlayList;
int lat=0;
int lng=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
map = (MapView) findViewById(R.id.mapView);
map.setBuiltInZoomControls(true);
overlayList = map.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin2);
CustomPinpoint itemizedoverlay = new CustomPinpoint(drawable,this);
double lat_coordinates[] ={27.700556,28.2642635,30.0018168,29.776669,29.4096819,29.4560611};
double lng_coordinates[] ={85.3630,83.9735195,80.7382742,81.2518833,81.8115051,80.5403779};
String place_name[] ={"kathmandu","Pokhara","Darchula","Bajhang","Bajura","Baitadi"};
String place_info[] ={"Its an capital of Nepal","Its and tourist place of Nepal","Its one of the beautiful place in country side","CHD District Target:10 51,960, VDCs/Muncipalities reported:41/41","CHD District Target: 71,280, VDCs/Muncipalities reported: 47/47","CHD District Target:10 51,960, VDCs/Muncipalities reported:41/41","CHD District Target: 71,280, VDCs/Muncipalities reported: 7/7","CHD District Target:10 21,960, VDCs/Muncipalities reported:44/41","CHD District Target: 33,3123, VDCs/Muncipalities reported: 47/47"};
try{
for(int i=0; i<place_name.length; i++)
{
GeoPoint point = new GeoPoint((int)(lat_coordinates[i]*1E6),(int)(lng_coordinates[i]*1E6));
OverlayItem overlayitem = new OverlayItem(point, place_name[i], place_info[i]);
itemizedoverlay.addOverlay(overlayitem);
}
}catch(NullPointerException e){
e.getStackTrace();
}
finally{
overlayList.add(itemizedoverlay);
}
controller = map.getController();
controller.animateTo(new GeoPoint((int)(lat_coordinates[0]*1E6),(int)(lng_coordinates[0]*1E6)));
controller.setZoom(8);
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
}
Create new class...
package org.nip.gmap;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
//import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CustomPinpoint extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
public CustomPinpoint(Drawable defaultMarker, Context context) {
super(boundCenter(defaultMarker));
c= context;
}
// public CustomPinpoint(Drawable M, Context context) {
//
// this(M);
// c= context;
// }
public void addOverlay (OverlayItem overlay)
{
pinpoints.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
// TODO Auto-generated method stub
return pinpoints.size();
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
OverlayItem item = pinpoints.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
OnClickListener for pushpin
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();
}
}
};
}