mapview.getoverlays() null pointer exception - android

Hi all I am trying to implement an overlay onto my google map. However I am receiving a fatal error at runtime and it seems to be some sort of NullPointerException. The app runs properly when I remove the "overlayList = mapView.getOverlays();" and "overlayList.add(t);" lines of code. Any help is greatly appreciated!
Main Activity:
public class CSActivity extends MapActivity implements LocationListener {
MapController mapController;
MapView mapView;
LocationManager locationManager;
MyLocationOverlay myLocationOverlay;
MyLocationOverlay compass;
private Button click_but;
private Button exit_but;
long start;
long stop;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
String towers;
int lat;
int lng;
public void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.main); // bind the layout to the activity
click_but = new Button(this);
click_but = (Button)findViewById(R.id.clickBtn);
exit_but = new Button(this);
exit_but = (Button)findViewById(R.id.exitBtn);
d = getResources().getDrawable(R.drawable.markerblue);
Touchy t = new Touchy();
overlayList = mapView.getOverlays();
overlayList.add(t);
/*compass = new MyLocationOverlay(CSActivity.this, mapView);
overlayList.add(compass);*/
// Configure the Map
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(20); // Zoom 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
Criteria crit = new Criteria();
towers = locationManager.getBestProvider(crit, false);
Location L = locationManager.getLastKnownLocation(towers);
if (L != null){
lat = (int) (L.getLatitude()*1E6);
lng = (int) (L.getLongitude()*1E6);
GeoPoint ourLocation = new GeoPoint(lat, lng);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's up", "2nd String");
MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(CSActivity.this, "Couldn't get provider", Toast.LENGTH_SHORT).show();
}
final CSActivity home = this;
exit_but.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setClass(home, homeActivity.class);
startActivity(intent);
}
});
click_but.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v)
{
}
});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
locationManager.requestLocationUpdates(towers, 500, 1, this);
}
#Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
locationManager.removeUpdates(this);
}
class Touchy 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 = mapView.getProjection().fromPixels(x, y);
}
if (e.getAction() == MotionEvent.ACTION_UP){
stop = e.getEventTime();
}
if (stop - start > 1000){
//Perform action
AlertDialog alert = new AlertDialog.Builder(CSActivity.this).create();
alert.setTitle("Pick an Option");
alert.setMessage("I said pick!");
alert.setButton("place a pinpoint", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayItem = new OverlayItem(touchedPoint, "What's up", "2nd String");
MyItemizedOverlay custom = new MyItemizedOverlay(d, CSActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton2("get address", new DialogInterface.OnClickListener() {
#Override
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 t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally{
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
lat = (int) (location.getLatitude() *1E6);
lng = (int) (location.getLongitude()*1E6);
}
#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
}
}
Itemized Overlay Activity:
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public MyItemizedOverlay(Drawable m, Context context) {
// TODO Auto-generated constructor stub
this(m);
c = context;
}
#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();
}
public void insertPinpoint(OverlayItem item) {
pinpoints.add(item);
this.populate();
}
}
Main XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center" >
<com.google.android.maps.MapView
android:id="#+id/mapView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:apiKey="(key here)"
android:clickable="true"
android:enabled="true" />
<Button
android:id="#+id/clickBtn"
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:background="#drawable/blue"
android:text="Click" />
<Button
android:id="#+id/exitBtn"
style="#style/ButtonText"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:background="#drawable/red"
android:text="Home" />
</RelativeLayout>

mapView is null so get NPE first give refrences from xml file
mapView = (MapView) findViewById(R.id.mapView);
then get overlays
overlayList = mapView.getOverlays();
and
if(null!=overlayList&&overlayList.size()!=0){
overlayList.add(t);
}
Why NullPointerException ?

You are getting Overlay of mapview before define MapView so, you will got null pointer expection..
So first define mapview control after then use it.
mapView = (MapView) findViewById(R.id.mapView);
overlayList = mapView.getOverlays();

Related

How can i change an icon to a different icon in googlemaps

I would like to know is how can I add various different icons to google maps? at the moment i can add one, but want to add different ones selected from a list or whatever to place on the map.
here is my code for MainActivity:
public class MainActivity extends MapActivity implements LocationListener {
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x, y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
String towers;
int lat;
int longi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
map = (MapView) findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
Touchy t = new Touchy();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(MainActivity.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint((int)(-24.0110 * 1E6), (int)(31.4850 * 1E6));
controller.animateTo(point);
controller.setZoom(10);
d = getResources().getDrawable(R.drawable.icon);
//Placing PinPoint at location
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location location = lm.getLastKnownLocation(towers);
if (location != null){
lat = (int) (location.getLatitude() *1e6);
longi = (int) (location.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's Up", "2nd String");
CustomPinPoint custom = new CustomPinPoint(d, MainActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}else{
Toast.makeText(MainActivity.this, "Couldn't Get Provider", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
compass.enableCompass();
// TODO Auto-generated method stub
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this);
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class Touchy 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(MainActivity.this).create();
alert.setTitle("Pick an Option");
alert.setMessage("Option has been Picked");
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, "What's Up", "2nd String");
CustomPinPoint custom = new CustomPinPoint(d, MainActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
});
alert.setButton(DialogInterface.BUTTON_NEUTRAL, "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 t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.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 onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int) (l.getLatitude() *1E6);
longi = (int) (l.getLongitude() *1E6);
GeoPoint ourLocation = new GeoPoint(lat, longi);
OverlayItem overlayItem = new OverlayItem(ourLocation, "What's Up", "2nd String");
CustomPinPoint custom = new CustomPinPoint(d, MainActivity.this);
custom.insertPinpoint(overlayItem);
overlayList.add(custom);
}
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
}
}
And for my CustomPinPoint class:
import java.util.ArrayList;
import android.content.Context;
import android.graphics.drawable.Drawable;
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) {
super(boundCenter(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinPoint(Drawable m, Context context) {
this(m);
c = context;
// TODO Auto-generated constructor stub
}
#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();
}
public void insertPinpoint(OverlayItem item){
pinpoints.add(item);
this.populate();
}
}
If someone can point me in the right direction or have a tutorial on hoe to do it would be really helpfull, as i am completey stump from this point on-wards!
Thanks.
You can use this library – Android MapView Balloons. This project provides an easy way to annotate map overlay items with a simple information balloon when using the Android Maps.
Edit: I see in your CustomPinPoint class you do not have the createItem programmed. Technically, your "CustomPinPoint" class is an overlay class; it's a single layer with multiple pinpoints. You create the layer, and add points to that layer.
Use this:
#Override
protected void createItem(Object o, Drawable d) {
OverlayItem i = new OverlayItem(<Geopoint location>,<name>,<title>);
i.setMarker(d);
pinpoints.add(i);
}
This adds a pinpoint to your layer, with a custom marker. You should populate() the layer as soon as you're done adding all the icons.
So:
CustomPinPoint pinpoint = new CustomPinPoint();
[...]
In your Map activity
pinpoint.createItem(o, d); //Where o is the object info you want the marker to be about, and d is the custom drawable.
[...]
In your Map activity
map.getOverlays(pinpoint);
Something like that. I'm really bad at explaining things, but I hope this makes sense.

Getting user current location on google mapview

Hi I have been trying to get and pinpoint the location of the phone (user current location) however I have no luck. I hope somebody can help me with the code.
Just to add some more, I am receiving a "Couldn't get connection factory client" error. Does this have something to do with the ability to return the user location?
If it helps I have been following the tutorial by thenewboston.
Or does this have something to do with my API key? But I can receive the map properly, but cannot pinpoint the user's current location
The main code:
public class Map extends MapActivity implements LocationListener{
MapView map;
long start;
long stop;
MyLocationOverlay compass;
MapController controller;
int x,y;
GeoPoint touchedPoint;
Drawable d;
List<Overlay> overlayList;
LocationManager lm;
LocationListener ll;
String towers;
int lat = 0;
int longi = 0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_map);
map = (MapView)findViewById(R.id.mapview);
map.setBuiltInZoomControls(true);
touch t = new touch();
overlayList = map.getOverlays();
overlayList.add(t);
compass = new MyLocationOverlay(Map.this, map);
overlayList.add(compass);
controller = map.getController();
GeoPoint point = new GeoPoint(832332,4121093);
controller.animateTo(point);
controller.setZoom(8);
d = getResources().getDrawable(R.drawable.pointer);
//placing location
lm =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
Criteria crit = new Criteria();
towers = lm.getBestProvider(crit, false);
Location loc = lm.getLastKnownLocation(towers);
if(loc != null){
lat = (int) (loc.getLatitude() *1E6);
longi = (int)(loc.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}else{
Toast.makeText(Map.this, "Location is null", Toast.LENGTH_LONG).show();
lm.requestLocationUpdates(towers, 1500, 1, this);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
compass.disableCompass();
super.onPause();
lm.removeUpdates(this);
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
compass.enableCompass();
super.onResume();
lm.requestLocationUpdates(towers, 500, 1, this);
}
I think you can ignore the alertdialog
public 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 >1200){
AlertDialog alert = new AlertDialog.Builder(Map.this).create();
alert.setTitle("Option");
alert.setMessage("Pick the option");
alert.setCanceledOnTouchOutside(true);
alert.setButton("Place pointer pinpoint",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
OverlayItem overlayitem = new OverlayItem(touchedPoint , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
});
alert.setButton2("Get address",
new DialogInterface.OnClickListener() {
#Override
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 t = Toast.makeText(getBaseContext(), display, Toast.LENGTH_LONG);
t.show();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
}
}
});
alert.setButton3("Toggle View",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
if(map.isSatellite()){
map.setSatellite(false);
map.setStreetView(true);
}else{
map.setStreetView(false);
map.setSatellite(true);
}
}
});
alert.show();
return true;
}
return false;
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_map, menu);
return true;
}
#Override
public void onLocationChanged(Location l) {
// TODO Auto-generated method stub
lat = (int)(l.getLatitude()*1E6);
longi = (int)(l.getLongitude()*1E6);
GeoPoint location = new GeoPoint(lat, longi);
OverlayItem overlayitem = new OverlayItem(location , "wassup", "2nd string");
CustomPinPoint custom = new CustomPinPoint(d, Map.this);
custom.insertPinPoint(overlayitem);
overlayList.add(custom);
}
#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
}
}
The CustomPinPoint code :
public class CustomPinPoint extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> pinpoints = new ArrayList<OverlayItem>();
private Context c;
// tesst google code
public CustomPinPoint(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
// TODO Auto-generated constructor stub
}
public CustomPinPoint(Drawable defaultMarker, Context context) {
// TODO Auto-generated constructor stub
this(defaultMarker); //original code
}
#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();
}
public void insertPinPoint(OverlayItem item){
pinpoints.add(item);
// this.populate(); // original code
// test code
populate();
}
#Override
protected boolean onTap(int index){
OverlayItem item = pinpoints.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(c);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
public void addOverlay(OverlayItem overlay) {
// TODO Auto-generated method stub
pinpoints.add(overlay);
populate();
}
}
XML code:
<com.google.android.maps.MapView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/mapview"
android:enabled="true"
android:clickable="true"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:apiKey="0t9rHfGlUPgisa8P9MRAsSxhRXTVCL0XJog7uiA"
/>
Here is the example how to do that easily, try to implement this logic into your project:
public class MyMapActivity extends MapActivity {
private MapView map;
private MapController controller;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mymap);
initMapView();
initMyLocation();
map.invalidate();
}
private void initMapView() {
map = (MapView) findViewById(R.id.map);
controller = map.getController();
map.setSatellite(true);
map.setBuiltInZoomControls(true);
}
private void initMyLocation() {
final MyLocationOverlay overlay = new MyLocationOverlay(this, map);
overlay.enableMyLocation();
//overlay.enableCompass(); // does not work in emulator
overlay.runOnFirstFix(new Runnable() {
public void run() {
// Zoom in to current location
controller.setZoom(15);
controller.animateTo(overlay.getMyLocation());
}});
}
}
Well this is embarrassing, it turns out that my code is correct and the problem was that the device's GPS wasn't turned on. Well I hope my code can help anyone in need. Cheers!

Map View Marker in Current Location

I'm using this codes to view the current location of the user. But I also need to put a marker on it. I already saw a few tutorial regarding this but I still don't get it.
Here's my Activity
public class MapViewActivity extends MapActivity {
#Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.mapview);
//------------Start Displaying Map View--------------//
LocationManager locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint test= new GeoPoint(
lat,lng);
MapView mapview = (MapView) findViewById(R.id.mvmap);
MapController mapcontrol = mapview.getController();
mapcontrol.animateTo(test);
mapcontrol.setZoom(10);
mapview.setStreetView(true);
mapview.setSatellite(true);
mapview.setBuiltInZoomControls(true);
}
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
}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
use this class for ItemizedOverlay.
public class CustomItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mapOverlays = new ArrayList<OverlayItem>();
private Context context;
public CustomItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
public CustomItemizedOverlay(Drawable defaultMarker, Context context) {
this(defaultMarker);
this.context = context;
}
#Override
protected OverlayItem createItem(int i) {
return mapOverlays.get(i);
}
#Override
public int size() {
return mapOverlays.size();
}
#Override
protected boolean onTap(int index) {
OverlayItem item = mapOverlays.get(index);
Log.e(" on tap item value ", "" + mapOverlays.get(index) + " Index "
+ 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();
}
public void removeOverlay() {
mapOverlays.clear();
// this.populate();
}
}
In your MapViewActivity ,declare ,
CustomItemizedOverlay itemizedOverlay;
List<Overlay> mapOverlays;
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.marker);
itemizedOverlay = new CustomItemizedOverlay(drawable, this);
OverlayItem overlayitem = new OverlayItem(test," "," ");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);

Android Radius circle around Geopoint

This is the code i written to get the gps coordinates of the mobile and point the place where you are. But in improvement I need to get 1km radius circle. How can i get it?
package m.a.p;
public class MappingActivity extends MapActivity {
MapController mControl;
GeoPoint GeoP;
MapView mapV;
Drawable d;
List<Overlay> overlaylist;
public double lat;
public double lng;
Button checkin, addplace;
private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 1; // in
// Meters
private static final long MINIMUM_TIME_BETWEEN_UPDATES = 10000; // in
// Milliseconds
protected LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mapV = (MapView) findViewById(R.id.mapview);
checkin = (Button) findViewById(R.id.check);
addplace = (Button) findViewById(R.id.addp);
overlaylist = mapV.getOverlays();
d = getResources().getDrawable(R.drawable.point);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
MINIMUM_TIME_BETWEEN_UPDATES,
MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, new MyLocationListener());
Location location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
}
Button check = (Button) findViewById(R.id.check);
Button addplace = (Button) findViewById(R.id.addp);
Button nearby = (Button) findViewById(R.id.point);
check.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView result = (TextView) findViewById(R.id.result);
result.setText("Checked the Plce");
}
});
addplace.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
TextView result = (TextView) findViewById(R.id.result);
result.setText("Added the Plce");
}
});
nearby.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
TextView result = (TextView) findViewById(R.id.result);
result.setText("Nearby the Plce");
}
});
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
public class MyLocationListener implements LocationListener {
public void onLocationChanged(Location location) {
String message = String.format("You are Here");
Toast.makeText(MappingActivity.this, message, Toast.LENGTH_LONG)
.show();
GeoP = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mControl = mapV.getController();
mControl.animateTo(GeoP);
mControl.setZoom(19);
OverlayItem overlayItem = new OverlayItem(GeoP, "You are Here",
"Point");
CustomPinpoint custom = new CustomPinpoint(d, MappingActivity.this);
custom.insertPinpoint(overlayItem);
overlaylist.add(custom);
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
}
custompinpoint
public class CustomPinpoint extends ItemizedOverlay{
private ArrayList<OverlayItem> pinpoints = new ArrayList <OverlayItem>();
private Context c;
public CustomPinpoint(Drawable defaultMarker) {
super(boundCenter(defaultMarker));
}
public CustomPinpoint(Drawable m, Context context){
this(m);
c = context;
}
#Override
protected OverlayItem createItem(int i) {
// TODO Auto-generated method stub
return pinpoints.get(i);
}
#Override
public int size() {
return pinpoints.size();
}
public void insertPinpoint(OverlayItem item){
pinpoints.add(item);
this.populate();
}
}
Try to use a custom MapOverlay to draw your location and a circle around it whit overriding onDraw() method:
public class MyOwnLocationOverlay extends MyLocationOverlay{
private MapView mapView;
private Paint circlePainter;
private Point screenCurrentPoint;
private GeoPoint geoCurrentPoint;
private int meters;
public MyOwnLocationOverlay(Context context, MapView mapView) {
super(context, mapView);
this.mapView = mapView;
}
// This method is used to get user submitted radius from our application
public void setMeters(int meters) {
this.meters = meters;
}
#Override
public synchronized boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when) {
// Set the painter to paint our circle. setColor = blue, setAlpha = 70 so the background
// can still be seen. Feel free to change these settings
circlePainter = new Paint();
circlePainter.setAntiAlias(true);
circlePainter.setStrokeWidth(2.0f);
circlePainter.setColor(0xff6666ff);
circlePainter.setStyle(Style.FILL_AND_STROKE);
circlePainter.setAlpha(70);
// Get projection from the mapView.
Projection projection = mapView.getProjection();
// Get current location
geoCurrentPoint = getMyLocation();
screenCurrentPoint = new Point();
// Project the gps coordinate to screen coordinate
projection.toPixels(geoCurrentPoint, screenCurrentPoint);
int radius = metersToRadius(geoCurrentPoint.getLatitudeE6() /1000000);
// draw the blue circle
canvas.drawCircle(screenCurrentPoint.x, screenCurrentPoint.y, radius, circlePainter);
return super.draw(canvas, mapView, shadow, when);
}
// hack to get more accurate radius, because the accuracy is changing as the location
// getting further away from the equator
public int metersToRadius(double latitude) {
return (int) (mapView.getProjection().metersToEquatorPixels(meters) * (1/ Math.cos(Math.toRadians(latitude))));
}
}
see this link for more details

Display Dialog Box when i click on the maps place marker icon?

When I click the certain place in the map in android it shows the alert Dialog ? You want to save the location into particular list for example My place or Favorite so that I can move that place to particular list in.
Thanks in Advance......
public class MapViewer extends MapActivity {
MapView mapView;
MapController mapController;
GeoPoint mgeoPoint;
Drawable marker;
MyLocationOverlay mLocationOverlay;
MotionEvent e;
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
setContentView(R.layout.main);
mapView = (MapView) findViewById(R.id.mapView);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
marker = getResources().getDrawable(R.drawable.pushpin);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
.getIntrinsicHeight());
mapView.getOverlays().add(new MapOverlay(marker));
mLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(mLocationOverlay);
setViewLocation();
}
#Override
protected Dialog onCreateDialog(int id) {
// TODO Auto-generated method stub
switch (id) {
case 0:
return new AlertDialog.Builder(this).setTitle("Hello").setIcon(
R.drawable.ic_launcher).setPositiveButton("Yes",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
}).setCancelable(true).setNegativeButton("Cancel",
new OnClickListener() {
#Override
public void onClick(DialogInterface dialog , int which) {
// TODO Auto-generated method stub
}
})
.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Dismiss",
Toast.LENGTH_SHORT).show();
}
}).create();
default:
break;
}
return null;
}
private void setViewLocation() {
String[] coordinates = { "22.716221", "75.896816" };
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
mgeoPoint = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
mapController.animateTo(mgeoPoint);
mapController.setZoom(15);
mapView.invalidate();
}
#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);
ListofGeopoints.add(new OverlayItem(getPoint(22.716221, 75.896816),
"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();
}
}
}
Have you tried to override the onTap method in your customOverlays ?
public class CustomOverlays extends ItemizedOverlay<OverlayItem>
{
#Override
public boolean onTap(GeoPoint arg0, MapView arg1) {
// TODO Auto-generated method stub
return super.onTap(arg0, arg1);
}
}

Categories

Resources