I want to show a marker on google map position obtained from xml after parsing. So I store latitude and longitude in an arrylist. I want to show but it forse close
I pass lat and long from geopoint so please can you take a look where is wrong in my code
public class XMLParsingExample1 extends MapActivity {
/**
* Create Object For SiteList Class
*/
SitesList sitesList = null;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private String ss1;
private String ss2;
GeoPoint p;
class MapOverlay extends com.google.android.maps.Overlay {
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.marker);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
return true;
}
}
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
/** Create a new layout to display the view */
try {
/** Handling XML */
SAXParserFactory spf = SAXParserFactory.newInstance();
SAXParser sp = spf.newSAXParser();
XMLReader xr = sp.getXMLReader();
/** Send URL to parse XML Tags */
URL sourceUrl = new URL(
"http://site4demo.com/artealdiaonline/output.php?lat=-34.6394879&lng=-58.3617837kkj");
/** Create handler to handle XML Tags ( extends DefaultHandler ) */
MyXMLHandler myXMLHandler = new MyXMLHandler();
xr.setContentHandler(myXMLHandler);
xr.parse(new InputSource(sourceUrl.openStream()));
} catch (Exception e) {
System.out.println("XML Pasing Excpetion = " + e);
}
/** Get result from MyXMLHandler SitlesList Object */
sitesList = MyXMLHandler.sitesList;
ArrayList<Integer> Latitude = new ArrayList<Integer>();
ArrayList<Integer> Longtitude = new ArrayList<Integer>();
for (int i = 0; i < sitesList.getName().size(); i++) {
// **Is this correct??**
ss1 = sitesList.getName().get(i);
}
for (int i = 0; i < sitesList.getWebsite().size(); i++) {
ss2 = sitesList.getWebsite().get(i);
}
RelativeLayout linearLayout = (RelativeLayout) findViewById(R.id.mainlayout);
mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setStreetView(true);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, new GeoUpdateHandler());
//Here i pass latitude and longitude value for displaying in map
String coordinates[] = {ss1, ss2};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mapController.animateTo(p);
mapController.setZoom(17);
//---Add a location marker---
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#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);
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) {
}
}
}
sites list is
public class SitesList {
/** Variables */
private ArrayList<String> Latitude = new ArrayList<String>();
private ArrayList<String> Longitude = new ArrayList<String>();
private ArrayList<String> category = new ArrayList<String>();
/** In Setter method default it will return arraylist
* change that to add */
public ArrayList<String> getName() {
return Latitude;
}
public void setName(String name) {
this.Latitude.add(name);
}
public ArrayList<String> getWebsite() {
return Longitude;
}
public void setWebsite(String website) {
this.Longitude.add(website);
}
public ArrayList<String> getCategory() {
return category;
}
public void setCategory(String category) {
this.category.add(category);
}
}
I can see at least one case, where exception can be thrown.
If you have no any elements in Latitude and/or Longitude lists in SitesList class, or String values in those lists can't be parsed to double, the following lines will throw NumberFormatException
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
Related
I've managed to write an android app using it to trace user location and show it on the map using a marker. Here is the relevant code:
public class MainActivity extends Activity implements LocationListener {
public MapView mapView;
private LocationManager locationManager;
MyItemizedOverlay myItemizedOverlay = null;
Drawable marker;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapView = (MapView) this.findViewById(R.id.mapview);
mapView.setUseDataConnection(false);
mapView.setClickable(true);
mapView.setBuiltInZoomControls(true);
mapView.setMultiTouchControls(true);
mapView.setUseDataConnection(false);
mapView.setFocusable(true);
mapView.setFocusableInTouchMode(true);
mapView.getController().setZoom(16); // set initial zoom-level, depends
// on your need
marker = getResources().getDrawable(android.R.drawable.star_on);
int markerWidth = 1;
int markerHeight = 1;
marker.setBounds(0, markerHeight, markerWidth, 0);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0,
0, this); // You can also use LocationManager.GPS_PROVIDER and
// LocationManager.PASSIVE_PROVIDER
}
#Override
public void onLocationChanged(Location location) {
int lat = (int) (location.getLatitude() * 1E6);
int lng = (int) (location.getLongitude() * 1E6);
GeoPoint point = new GeoPoint(lat, lng);
mapView.getController().setCenter(point);
mapView.getController().animateTo(point);
mapView.invalidate();
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
mapView.getOverlays().clear();
mapView.getOverlays().add(myItemizedOverlay);
myItemizedOverlay.addItem(point, "myPoint1", "myPoint1");
TextView tv1 = (TextView) findViewById(R.id.myLat);
tv1.setText("Lat is " + lat);
TextView tv2 = (TextView) findViewById(R.id.myLong);
tv2.setText("Long is " + lng);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
Now I need a way of getting latitude and longitude properties of a clicked location on the map.
I mean I need something similar to the following code(which exists for google map api) in osmdroid.
google.maps.event.addListener(map, 'click', function(event) {
YourHandler(event.latLng);});
You have to create an Overlay and override the onSingleTapConfirmed.
Try this:
Overlay touchOverlay = new Overlay(this){
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e, final MapView mapView) {
final Drawable marker = getApplicationContext().getResources().getDrawable(R.drawable.markericon);
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int)e.getX(), (int)e.getY());
String longitude = Double.toString(((double)loc.getLongitudeE6())/1000000);
String latitude = Double.toString(((double)loc.getLatitudeE6())/1000000);
System.out.println("- Latitude = " + latitude + ", Longitude = " + longitude );
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint((((double)loc.getLatitudeE6())/1000000), (((double)loc.getLongitudeE6())/1000000)));
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if(anotherItemizedIconOverlay==null){
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
}else{
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(getApplicationContext(), overlayArray,null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
// dlgThread();
return true;
}
};
mapView.getOverlays().add(touchOverlay);
If you implement MapEventsReceiver you can use the singleTapConfirmedHelper() function which directly gives you a GeoPoint object of the clicked location. Here is an example:
public class MapActivity extends AppCompatActivity implements MapEventsReceiver {
...
#Override
public boolean singleTapConfirmedHelper(GeoPoint p) {
mapController.animateTo(p);
return true;
}
}
I have an extremely weird issue.
First of all, when I zoom in and out of a MapView, the marker (overlay) moves to incorrect places (doesn't work well with scaling).
Secondly, the market is being drawn at the wrong position!
I'll post code below but first listen to this:
I'm in Islamabad. The GeoCoder also tells me I'm in Islamabad. But when I draw a circle around my location using overlays, it draws it in a city that's 100s of kilometers away.
Kindly help me with both the problems.
Here's the activity:
public class LocatePickup extends MapActivity implements LocationListener {
Geocoder gc;
MapView mapView;
MapController mc;
GeoPoint p;
double lat = 0;
double lng = 0;
LocationManager lm;
WebMethods wm;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.locate_pickup);
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapView.setStreetView(true);
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 1000L, 500.0f, this);
Location l = new Location(LocationManager.NETWORK_PROVIDER);
l = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
mc = mapView.getController();
p = new GeoPoint((int) (l.getLatitude()), (int) (l.getLongitude()));
mc.setCenter(p);
mc.setZoom(14);
MapOverlay myLocationOverlay = new MapOverlay();
List<Overlay> list = mapView.getOverlays();
list.add(myLocationOverlay);
gc = new Geocoder(this);
try {
List<Address> address = gc.getFromLocation(l.getLatitude(), l.getLongitude(), 1);
Toast.makeText(this, ""+address.get(0).getAddressLine(1), 1).show();
}
catch (IOException e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
class MapOverlay extends com.google.android.maps.Overlay {
Paint paint = new Paint();
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 218, 28, 28);
paint.setStyle(Paint.Style.STROKE);
//Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.pin);
canvas.drawCircle(myScreenCoords.x, myScreenCoords.y, 15, paint);
//(bmp, myScreenCoords.x, myScreenCoords.y - 256, paint);
canvas.drawText("Hey!", myScreenCoords.x, myScreenCoords.y, paint);
return true;
}
}
#Override
public void onLocationChanged(Location arg0) {
if(arg0 != null) {
Log.d("New Location: ", arg0.getLatitude() + " - " + arg0.getLongitude());
lat = arg0.getLatitude();
lng = arg0.getLongitude();
p = new GeoPoint((int) lat * 1000000, (int) lng * 1000000);
mc.animateTo(p);
}
}
#Override
public void onProviderDisabled(String provider) {
// empty
}
#Override
public void onProviderEnabled(String provider) {
// empty
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {
//empty
}
}
Once the code is complete, I'd like the user to be able to tap a spot on the map and get its address (the marker should move to that spot as well). But it should be accurate.
Since no one answered this question correctly..
For some reason, the normal Overlay class wasn't working for me the way it should have. I switched to ItemizedOverlay and now everything is perfect.
I'm no Android expert so I'd like someone with better experience to comment on this but, I feel that ItemizedOverlay is much better than the simple Overlay. With itemizedoverlay, zooming in and out of the mapview with an object drawn at a fixed point works the way it should, the pin (object) stays exactly where it should stay (that wasn't the case previously).
Here's some code for those who are looking for it. This is of course incomplete, and for a specific purpose, but you get the general idea.
`class CustomOverlay extends com.google.android.maps.ItemizedOverlay
{
private ArrayList mOverlays = new ArrayList();
Context mContext;
public CustomOverlay(Drawable defaultMarker)
{
super(defaultMarker);
}
public void addOverlay(OverlayItem overlay)
{
mOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i)
{
return mOverlays.get(i);
}
#Override
public int size()
{
return mOverlays.size();
}
public CustomOverlay(Drawable defaultMarker, Context context)
{
super(boundCenterBottom(defaultMarker));
mContext = context;
}
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
if (event.getAction() == 1)
{
p = mapView.getProjection().fromPixels((int) event.getX(),
(int) event.getY());
gc = new Geocoder(getBaseContext(), Locale.getDefault());
try
{
address = gc.getFromLocation(
(double) p.getLatitudeE6() / 1E6,
(double) p.getLongitudeE6() / 1E6, 1);
addressfound = true;
}
catch (IOException e)
{
addressfound = false;
e.printStackTrace();
}
if (address.size() != 0)
{
l1 = address.get(0).getAddressLine(0);
l2 = address.get(0).getAddressLine(1);
l3 = address.get(0).getAddressLine(2);
}
OverlayItem point = new OverlayItem(p, "Location", l1 + ", "
+ l2 + ", " + l3);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = getBaseContext().getResources()
.getDrawable(R.drawable.androidmarker);
CustomOverlay itemizedoverlay = new CustomOverlay(drawable,
getBaseContext());
itemizedoverlay.addOverlay(point);
mapOverlays.clear();
mapOverlays.add(itemizedoverlay);
mapView.invalidate();
}`
I am making an app in which i have a navigation screen where the user can give in multiple locations.
Those locations are stored in a array string.
I am using that string in my map class and i want to show al the locations on the map with a marker.
Only the last location stored in the array shows up.
Can anybody help me please.
My Navigation class
public class Navigatie extends Activity{
public static String plaats1;
public static String plaats2;
public GeoPoint p;
public static String[] plaats;
public int i = 0;
static final String[] COUNTRIES = new String[]
{
"Antwerpen", "Aalst", "Aartselaar", "Brussel", "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
};
// Here we create the layout, everything that's needed on the form is loaded in here.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.navigatie);
// Create an instance of the AutoCompleteTextView which is created in the layout file
AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete);
// Create an ArrayAdapter which we are using to autocomplete the textview
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
// put the adapter created above in the AutoCompleteTextView
textView.setAdapter(adapter);
// We create a new ImageButton which links to the map.java class
ImageButton imageButton = (ImageButton) findViewById(R.id.imageButton1);
// We give a onclicklistener method to the button imageButton
imageButton.setOnClickListener(new OnClickListener() {
// if the imageButton is clicked we start a new activity called "Map"
public void onClick(View v) {
/*
for (int j = 0; j<plaats.length; j++)
{
Map.plaats[j] = plaats[j];
}
*/
startActivity(new Intent(Navigatie.this, Map.class));
}
});
Button add = (Button)findViewById(R.id.toevoegen);
add.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText text1 = (EditText)findViewById(R.id.autocomplete);
plaats1 = text1.getText().toString();
if (plaats1 != "")
{
EditText text2 = (EditText)findViewById(R.id.editText1);
text2.append(plaats1 + "\n");
plaats = new String[20];
plaats[i] = plaats1;
Toast.makeText(Navigatie.this, plaats[i], Toast.LENGTH_SHORT).show();
i++;
text1.setText("");
}
}
});
Button clear = (Button)findViewById(R.id.verwijderen);
clear.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
EditText text2 = (EditText)findViewById(R.id.editText1);
text2.setText("");
Arrays.fill(plaats, null);
}
});
}
}
My Map class:
public class Map extends MapActivity {
private MapView mapView;
private MapController mc;
LocationManager locMgr;
MyLocationListener locLstnr;
private TextView tvlat;
private TextView tvlong;
public Navigatie nav;
public String locatie;
public int coordinates[] = new int[100];
public int counter = 0;
int gplat;
int gplon;
static final String[] COUNTRIES = new String[]
{
"Antwerpen", "Aalst", "Aartselaar", "Brussel", "Charleroi","duinkerke", "Gent", "Hasselt", "Ieper", ""
};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
// set the layout screen to map
setContentView(R.layout.map);
// Create an instance of the AutoCompleteTextView which is created in the layout file
AutoCompleteTextView textView=(AutoCompleteTextView)findViewById(R.id.autocomplete_country);
// Create an ArrayAdapter which we are using to autocomplete the textview
ArrayAdapter<String>adapter=new ArrayAdapter<String>(this,R.layout.item_list,COUNTRIES);
// put the adapter created above in the AutoCompleteTextView
textView.setAdapter(adapter);
// Setting the mapview1 to the instance of MapView
mapView = (MapView) findViewById(R.id.mapview1);
// giving a controller to mc
mc = mapView.getController();
// String location2 = Navigatie.getVariable();
for (int i = 0; i<Navigatie.plaats.length; i++)
{
if(Navigatie.plaats[i]!=null && !Navigatie.plaats[i].equals(""))
{
FindLocation(Navigatie.plaats[i]);
}
else
{
System.out.println("Locatie niet gevonden");
}
}
// create an instance of the find button created in the layout file
Button btn_find = (Button) findViewById(R.id.btn_find);
// Defining button click event listener for the find button
OnClickListener findClickListener = new OnClickListener()
{
public void onClick(View v)
{
// Getting reference to EditText to get the user input location
EditText etLocation = (EditText) findViewById(R.id.autocomplete_country);
// Getting user input location
String location = etLocation.getText().toString();
if(location!=null && !location.equals(""))
{
Toast.makeText(Map.this, "Inzoomend op " + location, Toast.LENGTH_SHORT).show();
new GeocoderTask().execute(location);
}
else
{
Toast.makeText(Map.this, "Locatie niet gevonden", Toast.LENGTH_SHORT).show();
}
}
};
// Setting button click event listener for the find button
btn_find.setOnClickListener(findClickListener);
// redraws the map
mapView.invalidate();
// sets the built in zoomcontrols on the screen
mapView.setBuiltInZoomControls(true);
Drawable makerDefault = this.getResources().getDrawable(R.drawable.pushpin);
MirItemizedOverlay itemizedOverlay = new MirItemizedOverlay(makerDefault);
GeoPoint point = null;
for (int i = 0; i<100; i++)
{
point = new GeoPoint(coordinates[i], coordinates[i+1]);
OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
itemizedOverlay.addOverlayItem(overlayItem);
i++;
}
mapView.getOverlays().add(itemizedOverlay);
MapController mc = mapView.getController();
mc.setCenter(point);
/*
String provider = LocationManager.GPS_PROVIDER;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestSingleUpdate(provider, null);
*/
List<Overlay> mapOverlays = mapView.getOverlays();
Projection projection = mapView.getProjection();
}
// when the form is created we put in the menu from the resources menu.
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
// we get the menu called main from the resources menu
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// we set the options for the menu parts
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
// if my location is touched, this code is executed
case R.id.my_location:
// creates a toast that displays "moving to current location"
Toast.makeText(Map.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
String provider = LocationManager.GPS_PROVIDER;
locMgr = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
locLstnr = new MyLocationListener();
locMgr.requestSingleUpdate(provider, null);
// locLstnr.gpsCurrentLocation();
return true;
// if normal view is touched, this code is executed
case R.id.normalview:
// creates a toast that displays "Map Normal Street View"
Toast.makeText(Map.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
// if the satellite view is enabled, we disable the satellite view so the normal view popups again
if(mapView.isSatellite()==true){
mapView.setSatellite(false);
}
return true;
case R.id.satellite:
// creates a toast that displays "Map Satellite view"
Toast.makeText(Map.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
// if the satellite view is disabled we enable the satellite view
if(mapView.isSatellite()==false){
mapView.setSatellite(true);
}
}
return true;
}
#Override
protected boolean isRouteDisplayed()
{
// TODO Auto-generated method stub
return true;
}
public class MyLocationListener implements LocationListener
{
public void onLocationChanged(Location loc)
{
loc.getLatitude();
loc.getLongitude();
String Text = "My current location is: " +
"Latitud = " + loc.getLatitude() +
"Longitud = " + loc.getLongitude();
Toast.makeText( getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
String coordinates[] = {""+loc.getLatitude(), ""+loc.getLongitude()};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
GeoPoint p = new GeoPoint(
(int) (lat * 1E6),
(int) (lng * 1E6));
mc.animateTo(p);
mc.setZoom(7);
mapView.invalidate();
}
public void onProviderDisabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Disabled",
Toast.LENGTH_SHORT ).show();
}
public void onProviderEnabled(String provider)
{
Toast.makeText( getApplicationContext(),
"Gps Enabled",
Toast.LENGTH_SHORT).show();
}
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
}
// My overlay Class starts
class MyMapOverlays extends com.google.android.maps.Overlay
{
GeoPoint location = null;
public MyMapOverlays(GeoPoint location)
{
super();
this.location = location;
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
super.draw(canvas, mapView, shadow);
// translate the screen pixels
Point screenPoint = new Point();
mapView.getProjection().toPixels(this.location, screenPoint);
//add the image
canvas.drawBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.pushpin),
screenPoint.x, screenPoint.y , null); //Setting the image location on the screen (x,y).
}
}
// My overlay Class ends
private class MirItemizedOverlay extends ItemizedOverlay
{
private List<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public MirItemizedOverlay(Drawable defaultMarker)
{
super(boundCenterBottom(defaultMarker));
}
#Override
protected OverlayItem createItem(int i)
{
return mOverlays.get(i);
}
#Override
public int size()
{
return mOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem)
{
mOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title)
{
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
}
/*
#Override
public boolean onTouchEvent(MotionEvent event, MapView mapView)
{
//---when user lifts his finger---
if (event.getAction() == 1)
{
GeoPoint p = mapView.getProjection().fromPixels(
(int) event.getX(),
(int) event.getY());
Toast.makeText(getBaseContext(),
p.getLatitudeE6() / 1E6 + "," +
p.getLongitudeE6() /1E6 ,
Toast.LENGTH_SHORT).show();
Geocoder geoCoder = new Geocoder(getBaseContext(), Locale.getDefault());
try
{
List<Address> addresses = geoCoder.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);
String strCompleteAddress= "";
if (addresses.size() > 0)
{
for (int i=0; i<addresses.get(0).getMaxAddressLineIndex();i++)
strCompleteAddress+= addresses.get(0).getAddressLine(i) + "\n";
}
Log.i("MyLocTAG => ", strCompleteAddress);
Toast.makeText(getBaseContext(), strCompleteAddress, Toast.LENGTH_LONG).show();
}
catch (IOException e)
{
Log.i("MyLocTAG => ", "this is the exception part");
e.printStackTrace();
}
return true;
}
else
return false;
}*/
}
//An AsyncTask class for accessing the GeoCoding Web Service
private class GeocoderTask extends AsyncTask<String, Void, List<Address>>
{
protected List<Address> doInBackground(String... locationName)
{
// Creating an instance of Geocoder class
Geocoder geocoder = new Geocoder(getBaseContext());
List<Address> addresses = null;
try {
//Getting a maximum of 3 Address that matches the input text
addresses = geocoder.getFromLocationName(locationName[0], 3);
}
catch (IOException e) {
e.printStackTrace();
}
return addresses;
}
protected void onPostExecute(List<Address> addresses)
{
//Getting Reference to MapView of the layout activity_main
MapView mapView = (MapView) findViewById(R.id.mapview1);
// Setting ZoomControls
mapView.setBuiltInZoomControls(true);
// Getting MapController for the MapView
MapController mc = mapView.getController();
// Getting Drawable object corresponding to a resource image
Drawable drawable = getResources().getDrawable(R.drawable.pushpin);
// Getting Overlays of the map
List<Overlay> overlays = mapView.getOverlays();
// Creating an ItemizedOverlay
LocationOverlay locationOverlay = new LocationOverlay(drawable,getBaseContext());
// Clearing the overlays
overlays.clear();
if(addresses==null || addresses.size()==0)
{
Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
// Redraws the map to clear the overlays
mapView.invalidate();
}
// Adding Markers on Google Map for each matching address
for(int i=0;i<addresses.size();i++)
{
Address address = (Address) addresses.get(i);
// Creating an instance of GeoPoint, to display in Google Map
GeoPoint p = new GeoPoint((int)(address.getLatitude()*1E6), (int)(address.getLongitude()*1E6));
String addressText = String.format("%s, %s",
address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
address.getCountryName());
// Creating an OverlayItem to mark the point
OverlayItem overlayItem = new OverlayItem(p, "Location",addressText);
// Adding the OverlayItem in the LocationOverlay
locationOverlay.addOverlay(overlayItem);
// Adding locationOverlay to the overlay
overlays.add(locationOverlay);
// Locate the first location
if(i==0)
mc.animateTo(p);
mc.setZoom(15);
}
// Redraws the map
mapView.invalidate();
}
}
public void FindLocation(String plaats)
{
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
plaats, 5);
//String add = "";
if (addresses.size() > 0) {
coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
counter++;
coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
counter++;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
a few hints:
On FindLocation add an else to catch not found locations:
public void FindLocation(String plaats) {
Geocoder geoCoder = new Geocoder(this, Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
plaats, 5);
//String add = "";
if (addresses.size() > 0) {
coordinates[counter] = (int) (addresses.get(0).getLatitude() * 1E6);
counter++;
coordinates[counter] = (int) (addresses.get(0).getLongitude() * 1E6);
counter++;
} else {
Log.v(TAG, "Site " + plaats + " not found!");
}
} catch (IOException e) {
e.printStackTrace();
}
}
Also in onCreate() loop over already defined locations, not the whole array:
for (int i = 0; i<count; i+=2)
{
point = new GeoPoint(coordinates[i], coordinates[i+1]);
OverlayItem overlayItem = new OverlayItem(point, "new place added", null);
itemizedOverlay.addOverlayItem(overlayItem);
}
I have to make a multiple marker google map using JSON parsing. Any one having helping code of it. So that i can gain an idea on it. The activity i have made is not working exactly what i want.
This is my activity
public class MapsActivity extends MapActivity{
private MapController mapControll;
private GeoPoint geoPoint=null;
private MapView mapview;
private MyItemizedOverlay userPicOverlay;
private MyItemizedOverlay nearPicOverlay;
private Drawable userPic,atmPic;
private OverlayItem nearatms[] = new OverlayItem[50];
public static Context context;
public double latitude;
public double longitude;
private List<String> lat = new ArrayList<String>();
private List<String> lon = new ArrayList<String>();
private String[] get_lati;
private String[] get_long;
#Override
protected void onCreate(Bundle icicle) {
// TODO Auto-generated method stub
super.onCreate(icicle);
context = getApplicationContext();
setContentView(R.layout.map);
lat.clear();
lon.clear();
Intent in = getIntent();
if(in!=null){
get_lati = in.getStringArrayExtra("LAT_KEY");
get_long = in.getStringArrayExtra("LONG_KEY");
System.out.println("lat===="+get_lati.length+" lon==="+get_long.length);
}
for(int i = 0;i<get_lati.length;i++){
String lt = null;
String ln = null;
lt =get_lati[i];
ln =get_long[i];
System.out.println("lt=="+lt+"==ln=="+ln);
}
showMap();
}
public void showMap() {
// TODO Auto-generated method stub
try {
double lat_dbl = Double.parseDouble(get_lati[0]);
double lon_dbl = Double.parseDouble(get_long[0]);
geoPoint = new GeoPoint((int)(lat_dbl * 1E6),(int)(lon_dbl * 1E6));
mapview = (MapView)findViewById(R.id.mapView);
mapControll= mapview.getController();
mapview.setBuiltInZoomControls(true);
mapview.setStreetView(true);
mapControll.setZoom(16);
mapControll.animateTo(geoPoint);
userPic = this.getResources().getDrawable(R.drawable.pin);
userPicOverlay = new MyItemizedOverlay(userPic);
OverlayItem overlayItem = new OverlayItem(geoPoint, "I'm Here!!!", null);
userPicOverlay.addOverlay(overlayItem);
mapview.getOverlays().add(userPicOverlay);
atmPic = this.getResources().getDrawable(R.drawable.pin);
nearPicOverlay = new MyItemizedOverlay(atmPic);
for (int i = 0; i < 5; i++) {
nearatms[i] = new OverlayItem(new GeoPoint((int)((latitude) * 1E6), i),"Name", null);//just check the brackets i just made change here so....
nearPicOverlay.addOverlay(nearatms[i]);
}
mapview.getOverlays().add(nearPicOverlay);
//Added symbols will be displayed when map is redrawn so force redraw now
mapview.postInvalidate();
} catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
public class MyItemizedOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> myOverlays ;
public MyItemizedOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
myOverlays = new ArrayList<OverlayItem>();
populate();
}
public void addOverlay(OverlayItem overlay){
myOverlays.add(overlay);
populate();
}
#Override
protected OverlayItem createItem(int i) {
return myOverlays.get(i);
}
// Removes overlay item i
public void removeItem(int i){
myOverlays.remove(i);
populate();
}
// Returns present number of items in list
#Override
public int size() {
return myOverlays.size();
}
public void addOverlayItem(OverlayItem overlayItem) {
myOverlays.add(overlayItem);
populate();
}
public void addOverlayItem(int lat, int lon, String title) {
try {
GeoPoint point = new GeoPoint(lat, lon);
OverlayItem overlayItem = new OverlayItem(point, title, null);
addOverlayItem(overlayItem);
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
#Override
protected boolean onTap(int index) {
// TODO Auto-generated method stub
String title = myOverlays.get(index).getTitle();
//Toast.makeText(MapActivity.this, title, Toast.LENGTH_LONG).show();
return super.onTap(index);
}
}
}
You are creating a geopoint with latitude but 'i' instead of longitude.
new GeoPoint((int)((latitude) * 1E6), i)
instead of:
new GeoPoint((int)((latitude) * 1E6), (int)((longitude) * 1E6)) // + some variation based on i
Thus all the points fall very near to each other.
I assume that you're using 'i' in order to create separate point near your location, and that in the final product you would use an ATM point DB. I suggest that you create a function that is supposed to retrieve ATM locations, and for testing purposes either return fixed (but real) locations, or randomize around your lat/lng. (This is also a better coding practice.)
For debug purposes, log the actual points you are creating, after you created them. if all lat/lng numbers look the same, you have a clue at what's going on. if only two points are logged... that's a different problem. :-)
I am trying to display multiple pin locations on the map i.e. my location and another location I get from the cloud server.
Based on the code below:
I keep getting a NullPointer Error message when I try to tokenize my string. This implies that my CloudTask activity is never fired.... I can't figure out why and the Eclipse Debugger won't step through the threads...any help is appreciated.
public class MapsActivity extends com.google.android.maps.MapActivity {
private static final String TAG = null;
private MapController mapController;
private MapView mapView;
private LocationManager locationManager;
private MyOverlays itemizedoverlay;
private MyLocationOverlay myLocationOverlay;
private MyLocationOverlay otherLocationOverlay;
private Handler handler;
private String message;
StringTokenizer tokens;
Integer p1 = null;
Integer p2;
GeoPoint point;
static Context mContext = null;
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);
mapView.setSatellite(true);
mapController = mapView.getController();
mapController.setZoom(14); // Zoon 1 is world view
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 2500,
0,(LocationListener) new GeoUpdateHandler());
//new Intent("android.intent.action.LOCATION_CHANGED");
//(LocationListener) new GeoUpdateHandler());
myLocationOverlay = new MyLocationOverlay(this, mapView);
mapView.getOverlays().add(myLocationOverlay);
handler = new Handler();
// new AsyncTask<Void, Void, String>() {
myLocationOverlay.runOnFirstFix(new Runnable(){
public void run(){
MyRequestFactory requestFactory = Util.getRequestFactory(mContext,
MyRequestFactory.class);
final CloudTask1Request request = requestFactory.cloudTask1Request();
Log.i(TAG, "Sending request to server");
request.queryTasks().fire(new Receiver<List<TaskProxy>>() {
#Override
public void onSuccess(List<TaskProxy> taskList) {
//message = result;
message = "\n";
for (TaskProxy task : taskList) {
message += task.getId()+","+task.getNote()+",";
}
}
});
//return message;
//}
if(message.length() == 0){
Log.i("MESSAGE","Did not get any points from cloud");
}
tokens = new StringTokenizer(message,",");
tokens.nextToken();
p1 = Integer.parseInt(tokens.nextToken());
p2 = Integer.parseInt(tokens.nextToken());
point = new GeoPoint(p1,p2);
mapView.getController().animateTo(point);
}
});
Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
itemizedoverlay = new MyOverlays(this, drawable);
createMarker();
myLocationOverlay.runOnFirstFix(new Runnable() {
public void run() {
mapView.getController().animateTo(
myLocationOverlay.getMyLocation());
}
});
//Drawable drawable = this.getResources().getDrawable(R.drawable.pushpin);
itemizedoverlay = new MyOverlays(this, drawable);
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() {
GeoPoint p = mapView.getMapCenter();
OverlayItem overlayitem = new OverlayItem(p, "", "");
itemizedoverlay.addOverlay(overlayitem);
if (itemizedoverlay.size() > 0) {
mapView.getOverlays().add(itemizedoverlay);
}
}
#Override
protected void onResume() {
super.onResume();
myLocationOverlay.enableMyLocation();
myLocationOverlay.enableCompass();
}
#Override
protected void onPause() {
super.onResume();
myLocationOverlay.disableMyLocation();
myLocationOverlay.disableCompass();
}
}
put these inside onSuccess()
if(message.length() == 0){
Log.i("MESSAGE","Did not get any points from cloud");
}
tokens = new StringTokenizer(message,",");
tokens.nextToken();
p1 = Integer.parseInt(tokens.nextToken());
p2 = Integer.parseInt(tokens.nextToken());
point = new GeoPoint(p1,p2);
mapView.getController().animateTo(point);