if i want to add overlay items on map using gps - android

here is my code enter code here
<
package ntryn.n;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MapController;
import com.google.android.maps.GeoPoint;
import android.content.Context;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.location.Geocoder;
import android.location.Address;
import com.google.android.maps.Overlay;
import android.graphics.Canvas;
import android.graphics.Point;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.Drawable;
import java.util.List;
import java.util.Locale;
import java.io.IOException;
import android.os.Bundle;
import android.widget.Toast;
public class ntryn extends MapActivity {
private MapView mapView;
private MapController mapController;
private LocationManager locationManager;
private LocationListener locationListener;
List<Overlay> mapOverlays;
Drawable drawable, drawable2 ;
HelloItemizedOverlay itemizedoverlay;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationListener = new GPSLocationListener();
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
0,
0,
locationListener);
mapView = (MapView) findViewById(R.id.mapView);
// enable Street view by default
mapView.setStreetView(true);
// enable to show Satellite view
// mapView.setSatellite(true);
// enable to show Traffic on map
// mapView.setTraffic(true);
mapView.setBuiltInZoomControls(true);
mapController = mapView.getController();
mapController.setZoom(16);
mapController = mapView.getController();
mapView.invalidate();
GeoPoint p;
String coordinates[] = {"30.084691643714909", "31.335958242416382"};
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);
// HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
MapOverlay mapOverlay = new MapOverlay();
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
mapView.invalidate();
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
private class GPSLocationListener implements LocationListener
{
public void onLocationChanged(Location location) {
if (location != null) {
GeoPoint point = new GeoPoint(
(int) (location.getLatitude() * 1E6),
(int) (location.getLongitude() * 1E6));
/* Toast.makeText(getBaseContext(),
"Latitude: " + location.getLatitude() +
" Longitude: " + location.getLongitude(),
Toast.LENGTH_SHORT).show();*/
mapController.animateTo(point);
mapController.setZoom(16);
// GeoPoint point1 = new GeoPoint{"30.084691643714909,31.335958242416382"};
// add marker
MapOverlay mapOverlay = new MapOverlay();
mapOverlay.setPointToDraw(point);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mapOverlay);
String address = ConvertPointToLocation(point);
Toast.makeText(getBaseContext(), address, Toast.LENGTH_SHORT).show();
mapView.invalidate();
}
}
public String ConvertPointToLocation(GeoPoint point) {
String address = "";
Geocoder geoCoder = new Geocoder(
getBaseContext(), Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocation(
point.getLatitudeE6() / 1E6,
point.getLongitudeE6() / 1E6, 1);
if (addresses.size() > 0) {
for (int index = 0; index < addresses.get(0).getMaxAddressLineIndex(); index++)
address += addresses.get(0).getAddressLine(index) + " ";
}
}
catch (IOException e) {
e.printStackTrace();
}
return address;
}
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
}
class MapOverlay extends Overlay
{
private GeoPoint pointToDraw;
private GeoPoint p1;
public void setPointToDraw(GeoPoint point) {
pointToDraw = point;
}
public GeoPoint getPointToDraw() {
return pointToDraw;
}
public void setp1(GeoPoint po1) {
p1 = po1;
}
public GeoPoint getp1() {
return p1;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
// convert point to pixels
Point screenPts = new Point();
mapView.getProjection().toPixels(pointToDraw, screenPts);
// add marker
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.dotred);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 24, null); // 24 is the height of image
return true;
}
}
}
whats wrong i'm doing i want to add other overlay rather than the one appear when i open the gps at my specific location

I'll try to answer based on the (little) info you gave.
Your code shows a MapOverlay that draws a bitmap over one point.
In the onCreate() method of your application you create MapOverlay and add it to the list of overlays of yout MapView, but you never call setPointToDraw() so you end up with a null GeoPoint
You are always clearing the list of overlays before addind a new one, so you always end up with one overlay.
If you want to display multiple points you can use ItemizedOverlay
If you want to display the users current location you can use MyLocationOverlay

Related

Getting 200 meter distance difference from the current location in GPS with map

This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.app.AlertDialog;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Criteria;
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.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MapViewActivity extends MapActivity implements LocationListener {
private MapView mapView;
Button search;
EditText address;
private LocationManager locationManager;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
address=(EditText)findViewById(R.id.enter_address);
if (address.getText().toString().trim().length() == 0) {
showMessage("Error", "Please enter address!");
return;
}
Geocoder geoCoder = new Geocoder(MapViewActivity.this,
Locale.getDefault());
try {
List<Address> addresses = geoCoder.getFromLocationName(
address.getText().toString(), 1);
// Getting latitude
double latitude = addresses.get(0).getLatitude();
// Getting longitude
double longitude = addresses.get(0).getLongitude();
if (addresses.size() > 0) {
GeoPoint p = new GeoPoint(
(int) ( latitude * 1E6),
(int) (longitude * 1E6));
// Getting MapController
MapController mapController =
mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(p);
//Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the
image of mark in the map
Drawable drawable =
MapViewActivity.this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark
the current location in the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the
overlay
OverlayItem currentLocation = new OverlayItem(p,
"Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
} catch (IOException e) {
e.printStackTrace();
}
catch(Exception e)
{
showMessage("Error", "Address not found!");
e.printStackTrace();
}
}
});
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);
// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);
// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);
if(location!=null){
onLocationChanged(location);
}
locationManager.requestLocationUpdates(provider, 20000, 0, this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
#Override
protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
return false;
}
#Override
public void onBackPressed() {
finish();
}
#Override
public void onDestroy() {
if (locationManager != null) {
locationManager.removeUpdates(this);
}
super.onDestroy();
}
#Override
public void onLocationChanged(Location location) {
// Getting latitude
double latitude = location.getLatitude();
// Getting longitude
double longitude = location.getLongitude();
// Setting latitude and longitude in the TextView tv_location
//tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude
);
// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));
// Getting MapController
MapController mapController = mapView.getController();
// Locating the Geographical point in the Map
mapController.animateTo(point);
// Applying a zoom
mapController.setZoom(15);
// Redraw the map
mapView.invalidate();
// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();
// Creating a drawable object to represent the image of mark in the map
Drawable drawable =
this.getResources().getDrawable(R.drawable.cur_position);
// Creating an instance of ItemizedOverlay to mark the current location in
the map
CurrentLocationOverlay currentLocationOverlay = new
CurrentLocationOverlay(drawable);
// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location",
"Latitude : " + latitude + ", Longitude:" + longitude);
// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);
// Clear Existing overlays in the map
mapOverlays.clear();
// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);
}
private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
alert.setTitle(title);
alert.setPositiveButton("OK", null);
alert.setMessage(message);
alert.show();
}
});
}
#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
}
}
and this is my CurrentLocationOverlay class
package com.ceolution.bhinstitute.crm;
import java.util.ArrayList;
import android.graphics.drawable.Drawable;
import android.util.Log;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
public CurrentLocationOverlay(Drawable defaultMarker) {
super(boundCenterBottom(defaultMarker));
}
// Executed, when populate() method is called
#Override
protected OverlayItem createItem(int arg0) {
return mOverlays.get(arg0);
}
#Override
public int size() {
return mOverlays.size();
}
public void addOverlay(OverlayItem overlay){
mOverlays.add(overlay);
populate(); // Calls the method createItem()
}
#Override
protected boolean onTap(int arg0) {
Log.d("Tapped", mOverlays.get(arg0).getSnippet());
return true;
}
}
// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
// getting GPS status
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
String provider;
if(!isGPSEnabled)
{
provider = LocationManager.NETWORK_PROVIDER;
}
else
provider=LocationManager.GPS_PROVIDER;
locationManager.requestLocationUpdates(provider, 20000, 0, this);
use above code after
// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);
hope this will help and also you can give alert to user to enable gps.

Android update map location with ASync Task

I have a map view which determines the user location in an ASyncTask and thereafter adds some markers at certain locations on the map. I cannot seem to update the map after a location is found. Is there any possible way to wait for the location to be found before running onPostExecute. I tried including the location listener in the MainMapView class without using an ASyncTask. This updates the map, but makes the map really slow and laggy. I assume that this is due to the fact that the map updates everytime a new location is found. Any Help is much appreciated.
import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MainMapView extends MapActivity{
private Location currentLocation;
private String serviceName;
private MapController mapController;
private List<Overlay> mapOverlays;
private ItemizedOverlay itemizedoverlay;
private LocationManager locationManager;
private HealthCarePractice[] practices;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map_view);
Bundle retItem = getIntent().getExtras();
serviceName = retItem.getString("serviceName");
//Log.e("This One", serviceName);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedoverlay = new ItemizedOverlay(drawable, this);
Context context = this;
MainMapViewTask task = new MainMapViewTask();
task.execute(context);
}
public class MainMapViewTask extends AsyncTask<Context, Integer, Void>
{
Context localContext;
#Override
protected Void doInBackground(Context... params) {
localContext = params[0];
// Aquire a reference to the system Location Manager
locationManager = (LocationManager) localContext.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null)
{
currentLocation = location;
locationManager.removeUpdates(this);
locationManager = null;
Geocoder geocoder = new Geocoder(MainMapView.this, Locale.getDefault());
List<Address> list;
if(currentLocation == null)
{
Log.e("Message", "Location not found");
}else{
try {
list = geocoder.getFromLocation(
currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
if (list != null && list.size() > 0) {
android.location.Address address = list.get(0);
//Log.e("Post Code", address.getPostalCode());
String poCode = address.getPostalCode();
if (poCode != null)
{
//Log.e("Post Code", address.getPostalCode());
String searchString = buildSearchString(serviceName, poCode.replaceAll(" ", ""));
//Log.e("posplit", poCode.split(" ")[0]);
Log.e("Search String", searchString);
RemoteData remoteData = new RemoteData("Location", searchString);
practices = remoteData.getPractices();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
Looper.myLooper();
Looper.prepare();
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
return null;
}
#Override
protected void onPostExecute(Void result) {
if(currentLocation != null)
{
GeoPoint currentPoint = new GeoPoint((int)(currentLocation.getLatitude()*1000000), (int)(currentLocation.getLongitude()*1000000));
mapController.setCenter(currentPoint);
mapController.setZoom(15);
for(int i=0; i< practices.length; i++)
{
int latitude = (int)(practices[i].getLatitude()*1000000);
int longitude = (int)(practices[i].getLongitude()*1000000);
currentPoint = new GeoPoint(latitude, longitude);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
String[] addressLines = practices[i].getAddress().getAddressLines();
StringBuilder sb = new StringBuilder();
for(int y=0; y<addressLines.length; y++)
{
sb.append(addressLines[y]);
sb.append('\n');
}
sb.append(practices[i].getAddress().getPostcode());
sb.append('\n');
sb.append("Telephone: ");
sb.append(practices[i].getTelephone());
OverlayItem currentOverlayItem = new OverlayItem(currentPoint,practices[i].getTitle(),sb.toString());
itemizedoverlay.addOverlay(currentOverlayItem);
mapOverlays.add(itemizedoverlay);
}
}
}
}
}
As an update, the following code works but the map is extremely laggy, there is a delay when a user tries to interact with the map by dragging to a new location
import android.os.Bundle;
import android.os.AsyncTask;
import android.os.Looper;
import android.util.Log;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapController;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class MainMapView extends MapActivity{
private Location currentLocation;
private String serviceName;
private MapController mapController;
private List<Overlay> mapOverlays;
private ItemizedOverlay itemizedoverlay;
private LocationManager locationManager;
private HealthCarePractice[] practices;
private boolean mapDrawn = false;
#Override
protected boolean isRouteDisplayed() {
return false;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_map_view);
Bundle retItem = getIntent().getExtras();
serviceName = retItem.getString("serviceName");
//Log.e("This One", serviceName);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
//mapView.setSatellite(true);
mapController = mapView.getController();
mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
itemizedoverlay = new ItemizedOverlay(drawable, this);
Context context = this;
/*
MainMapViewTask task = new MainMapViewTask();
task.execute(context);
*/
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
// Define a listener that responds to location updates
LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
// Called when a new location is found by the network location provider.
if (location != null)
{
currentLocation = location;
locationManager.removeUpdates(this);
locationManager = null;
Geocoder geocoder = new Geocoder(MainMapView.this, Locale.getDefault());
List<Address> list;
if(currentLocation == null)
{
Log.e("Message", "Location not found");
}else{
try {
list = geocoder.getFromLocation(
currentLocation.getLatitude(), currentLocation.getLongitude(), 1);
if (list != null && list.size() > 0) {
android.location.Address address = list.get(0);
//Log.e("Post Code", address.getPostalCode());
String poCode = address.getPostalCode();
if (poCode != null)
{
//Log.e("Post Code", address.getPostalCode());
String searchString = buildSearchString(serviceName, poCode.replaceAll(" ", ""));
//Log.e("posplit", poCode.split(" ")[0]);
Log.e("Search String", searchString);
RemoteData remoteData = new RemoteData("Location", searchString);
practices = remoteData.getPractices();
if(!mapDrawn)
{
mapDrawn = true;
if(currentLocation != null)
{
GeoPoint currentPoint = new GeoPoint((int)(currentLocation.getLatitude()*1000000), (int)(currentLocation.getLongitude()*1000000));
mapController.setCenter(currentPoint);
mapController.setZoom(15);
for(int i=0; i< practices.length; i++)
{
int latitude = (int)(practices[i].getLatitude()*1000000);
int longitude = (int)(practices[i].getLongitude()*1000000);
currentPoint = new GeoPoint(latitude, longitude);
mapController.setCenter(currentPoint);
mapController.setZoom(15);
String[] addressLines = practices[i].getAddress().getAddressLines();
StringBuilder sb = new StringBuilder();
for(int y=0; y<addressLines.length; y++)
{
sb.append(addressLines[y]);
sb.append('\n');
}
sb.append(practices[i].getAddress().getPostcode());
sb.append('\n');
sb.append("Telephone: ");
sb.append(practices[i].getTelephone());
OverlayItem currentOverlayItem = new OverlayItem(currentPoint,practices[i].getTitle(),sb.toString());
itemizedoverlay.addOverlay(currentOverlayItem);
mapOverlays.add(itemizedoverlay);
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public void onStatusChanged(String provider, int status, Bundle extras) {}
public void onProviderEnabled(String provider) {}
public void onProviderDisabled(String provider) {}
};
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locationListener);
}
I just noticed that the map was lagging due to the shadows being created for each of the marks, I do not know why this was caused, however removing the shadows for the markers using the following code in the OverlayItem class has solved my issue.
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow)
{
if(!shadow)
{
super.draw(canvas, mapView, false);
}
}
It must be noted that the shadows for the markers were horribly out of position. If anyone has a solution for incorporating shadows which are in the correct positions please do let me know. Regards Kush

How to get latitude and longitude from address on Android?

I am beginner in Android and I am working to create the Google Map which is able to mark the specific location from address.
For now, my following code is able to mark "empire state building" but nothing others..:<
I want to know how to get latitude and longitude from street address or full address, and mark it on the map.
I modified the manifest file for supporting Google Map view like INTERNET and ACCESS_COARSE_LOCATION
Thank you.
package cs2340.kiwi.HelloGoogleMaps;
import java.io.IOException;
import java.util.List;
import java.util.Locale;
import android.graphics.drawable.Drawable;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
public class HelloGoogleMapsActivity extends MapActivity {
/** Called when the activity is first created. */
#Override
protected boolean isRouteDisplayed() {
return false;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView mapView = (MapView) findViewById(R.id.mapview);
mapView.setBuiltInZoomControls(true);
List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.androidmarker);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, this);
Geocoder coder = new Geocoder(HelloGoogleMapsActivity.this, Locale.getDefault());
List<Address> address;
String strAddress = "empire state building";
GeoPoint p1 = new GeoPoint(0,0);
Double latitude;
Double longitude;
MapController mc = mapView.getController();
try {
address = coder.getFromLocationName(strAddress,5);
Address location = address.get(0);
latitude = location.getLatitude() * 1E6;
longitude = location.getLongitude() * 1E6;
p1 = new GeoPoint( latitude.intValue(),
longitude.intValue());
mc.animateTo(p1);
mapView.invalidate();
}
catch (IOException e){}
OverlayItem overlayitem2 = new OverlayItem(p1, "Hello", "not working");
itemizedoverlay.addOverlay(overlayitem2);
mapOverlays.add(itemizedoverlay);
}
}
Here is my another class
package cs2340.kiwi.HelloGoogleMaps;
import java.util.ArrayList;
import android.app.AlertDialog;
import android.content.Context;
import android.graphics.drawable.Drawable;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.OverlayItem;
public class HelloItemizedOverlay extends ItemizedOverlay {
private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();
private Context mContext;
public HelloItemizedOverlay(Drawable defaultMarker, Context context) {
super(boundCenterBottom(defaultMarker));
mContext = context;
}
public void addOverlay(OverlayItem overlay) {
mOverlays.add(overlay);
populate();
}
protected OverlayItem createItem(int i) {
return mOverlays.get(i);
}
public int size() {
return mOverlays.size();
}
protected boolean onTap(int index) {
OverlayItem item = mOverlays.get(index);
AlertDialog.Builder dialog = new AlertDialog.Builder(mContext);
dialog.setTitle(item.getTitle());
dialog.setMessage(item.getSnippet());
dialog.show();
return true;
}
}
http://maps.googleapis.com/maps/api/geocode/json?address=hyderabad&sensor=true_or_false
or
http://maps.googleapis.com/maps/api/geocode/xml?address=hyderabad&sensor=true_or_false
use any one of the url just replace your desired address and have a network hit then it will return a list of related lat and long from google server.
Try the geocoding service.Send an http request to the service then read the response and place a marker on the map.
To get Latitude and Longitude from street address or full address do following:
int maxResults = 5;
String address = "Example Road 15";
Geocoder geo = new Geocoder( context, Locale.getDefault() );
List<Address> addresses = geo.getFromLocationName( address, maxResults );
for ( Address a : adresses )
map.addMarker( new MarkerOptions().position( new LatLng( a.getLatitude(), a.getLongitude() ) ).title( "Hello" ).snippet( "Description about me!" ) );

Draw the route between 2 overlays

In my app I displayed on map 2 locations and I marked them with a marker. Now, I want to draw the route between them,and I don't know how can I do this. How should my function draw look like?
This is my code:
package com.ShoppingList.Maps;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
import com.ShoppingList.R;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.ItemizedOverlay;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;
import com.google.android.maps.Projection;
import java.util.ArrayList;
import java.util.List;
public class OnMap extends MapActivity {
private MapView map = null;
private MyLocationOverlay me = null;
//private myOverlay m = null;
double latitudine;
double longitudine;
double latshop;
double longshop;
String nameshop;
Canvas canvas = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.shopsonmap);
map = (MapView) findViewById(R.id.shopsonmap);
latitudine = getIntent().getDoubleExtra("latcurent", 0);
longitudine = getIntent().getDoubleExtra("longcurent", 0);
latshop = getIntent().getDoubleExtra("latshop", 0);
longshop = getIntent().getDoubleExtra("longshop", 0);
nameshop = getIntent().getStringExtra("nameshop");
GeoPoint p1 = new GeoPoint((int) latitudine, (int) longitudine);
GeoPoint p2 = new GeoPoint((int) latshop, (int) longshop);
map.getController().setCenter(getPoint(latitudine, longitudine));
map.getController().setZoom(15);
map.setBuiltInZoomControls(true);
map.setSatellite(false);
map.setStreetView(true);
map.invalidate();
Drawable marker = getResources().getDrawable(R.drawable.marker);
marker.setBounds(0, 0, marker.getIntrinsicWidth(), marker
.getIntrinsicHeight());
map.getOverlays().add(new SitesOverlay(marker));
me = new MyLocationOverlay(this, map);
map.getOverlays().add(me);
}
/*class myOverlay extends Overlay {
GeoPoint gp1;
GeoPoint gp2;
public myOverlay(GeoPoint gp1, GeoPoint gp2) {
this.gp1 = gp1;
this.gp2 = gp2;
}
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
Projection projection = mapView.getProjection();
Paint mPaint = new Paint();
Point from = new Point();
projection.toPixels(gp1, from);
mPaint.setColor(Color.BLUE);
Point to = new Point();
projection.toPixels(gp2, to);
mPaint.setStrokeWidth(9);
mPaint.setAlpha(120);
canvas.drawLine(from.x, from.y, to.x, to.y, mPaint);
super.draw(canvas, mapView, shadow);
}
}*/
#Override
public void onResume() {
super.onResume();
me.enableCompass();
}
#Override
public void onPause() {
super.onPause();
me.disableCompass();
}
#Override
protected boolean isRouteDisplayed() {
return (false);
}
private GeoPoint getPoint(double lat, double lon) {
return (new GeoPoint((int) (lat * 1000000.0), (int) (lon * 1000000.0)));
}
private class SitesOverlay extends ItemizedOverlay<OverlayItem> {
private List<OverlayItem> items = new ArrayList<OverlayItem>();
private Drawable marker = null;
public SitesOverlay(Drawable marker) {
super(marker);
this.marker = marker;
items.add(new OverlayItem(getPoint(latitudine, longitudine),
"Your location", "You are here!"));
items.add(new OverlayItem(getPoint(latshop, longshop), "The shop",
"The shop " + nameshop + " is here"));
populate();
}
#Override
protected OverlayItem createItem(int i) {
return (items.get(i));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
boundCenterBottom(marker);
}
#Override
protected boolean onTap(int i) {
Toast.makeText(OnMap.this, items.get(i).getSnippet(),
Toast.LENGTH_SHORT).show();
return (true);
}
#Override
public int size() {
return (items.size());
}
}
}
Thanks..
So let's suppose you are obtaining the locations (in JSON) from a REST web service. For this, I used Volley library to connect and obtain the response from the server.
Example of JSONArray response:
[ {...,"location":"44.924654,8.586219", ...},
{...,"location":"44.906177,8.157752", ...},
{...,"location":"44.906177,8.157752", ...}, {..., "location":
"44.956733,7.876227", ...}, {..., "location": "45.034424,7.671607",
...} ]
The step would be to set the first and the last locations as the markers, and the intermediate locations will draw the line between them.
Because location is obtained as a string, we have first to split the string and assign the part before the "," to the latitude and the rest as longitude.
public void onResponse(JSONArray response) {
if (response.length() > 0) {
try {
//creating the markers: for this I need the first and the last location
JSONObject firstLocationJson = response.getJSONObject(0);
JSONObject lastLocationJson = response.getJSONObject(response.length() - 1);
String[] firstLocationLatLng = firstLocationJson.getString("location").split(",");
Location firstLocation = new Location(LocationManager.GPS_PROVIDER);
firstLocation.setLatitude(Double.parseDouble(firstLocationLatLng[0]));
firstLocation.setLongitude(Double.parseDouble(firstLocationLatLng[1]));
String[] lastLocationLatLng = lastLocationJson.getString("location").split(",");
Location lastLocation = new Location(LocationManager.GPS_PROVIDER);
lastLocation.setLatitude(Double.parseDouble(lastLocationLatLng[0]));
lastLocation.setLongitude(Double.parseDouble(lastLocationLatLng[1]));
final float distance = firstLocation.distanceTo(lastLocation); //distance in meters
if (distance > 50000 && distance < 200000) { //distance bigger than 50 km
showMapView(response, firstLocation, lastLocation, 7);
} else if (distance > 300000) {
showMapView(response, firstLocation, lastLocation, 5);
}
} catch (JSONException e) {
// TODO
}
}
// TODO -
}
Now let's see the method that is drawing our MapView. Note that I am not inside an activity, and if I want to force code to be run on main thread (for updating the UI), I will use a Handler and a Runnable.
The method showMapView() is the one taking care of drawing the markers and the locations in between.
private void showMapView(JSONArray response, Location firstLoc, Location lastLoc, final int zoom) {
final LatLng latLng1 = new LatLng(firstLoc.getLatitude(), firstLoc.getLongitude());
final LatLng latLng2 = new LatLng(lastLoc.getLatitude(), lastLoc.getLongitude());
final MarkerOptions marker1 = new MarkerOptions().position(latLng1);
final MarkerOptions marker2 = new MarkerOptions().position(latLng2);
final PolylineOptions polylineOptions = new PolylineOptions();
final ArrayList<LatLng> points = new ArrayList<LatLng>();
//saving all the locations in an ArrayList
if (response.length() > 0) {
for (int i = 0; i < response.length(); i++) {
JSONObject locationsJson = null;
try {
locationsJson = response.getJSONObject(i);
} catch (JSONException e) {
e.printStackTrace();
}
String locationString = null;
try {
locationString = locationsJson.getString("location");
} catch (JSONException e) {
e.printStackTrace();
}
//here I am splitting the location string in a String array.
String[] locationLatLng = locationString.split(",");
Location loc = new Location(LocationManager.GPS_PROVIDER);
loc.setLatitude(Double.parseDouble(locationLatLng[0]));
loc.setLongitude(Double.parseDouble(locationLatLng[1]));
LatLng latLng = new LatLng(loc.getLatitude(), loc.getLongitude());
points.add(latLng);
}
}
Handler mainHandler = new Handler(Looper.getMainLooper());
Runnable myRunnable = new Runnable() {
#Override
public void run() {
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(GoogleMap googleMap) {
googleMap.addMarker(marker1);
googleMap.addMarker(marker2);
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng1, zoom));
googleMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng2, zoom));
polylineOptions.addAll(points);
polylineOptions.width(10);
polylineOptions.color(Color.BLUE);
googleMap.addPolyline(polylineOptions);
}
});
}
};
mainHandler.post(myRunnable);
}
The code is plain and clear, the points (intermediate locations) are draw using an object of type PolylineOptions and it is added to the map using this line: googleMap.addPolyline(polylineOptions);
The desired zoom level, is in the range of 2.0 to 21.0. Values below this range are set to 2.0, and values above it are set to 21.0. Increase the value to zoom in. Not all areas have tiles at the largest zoom levels.
read here about zoom
I have already given the answer of this question please read the following link blow
Draw line between two points in google map in android
I hope this is help.

give user defined annotation in mapview

I want to explore my cities on a mapview with multiple annotations but I unable to do that. Is any one suggest me that how can we do this in android with user defined longitude and latitude. I created a map view with one annotation but with system defined, I have to pass longitude and latitude from emulator control. how we send that with code with multiple annotation.
Here is my code:
package com.ex.maps;
import java.util.List;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Point;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.util.Log;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
import android.widget.ZoomControls;
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;
public class HelloGoogleMaps extends MapActivity implements LocationListener{
MapController mc;
GeoPoint p;
double lat;
double lng;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
MapView gMapView = (MapView) findViewById(R.id.mapview);
gMapView.setBuiltInZoomControls(true);
GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
gMapView.setSatellite(true);
mc = gMapView.getController();
mc.setCenter(p);
mc.setZoom(14);
LocationManager lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
LocationListener mlocListener = new HelloGoogleMaps();
//lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,mlocListener );
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, this);
ZoomControls zoomControls = (ZoomControls) gMapView.getZoomControls();
zoomControls.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT));
gMapView.addView(zoomControls);
gMapView.displayZoomControls(true);
MyLocationOverlay myLocationOverlay = new MyLocationOverlay();
List<Overlay> list = gMapView.getOverlays();
list.add(myLocationOverlay);
/*List<Overlay> mapOverlays = gMapView.getOverlays();
Drawable drawable = this.getResources().getDrawable(R.drawable.arrow_icon);
HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable);
//GeoPoint p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
OverlayItem overlayitem = new OverlayItem(point, "Hola, Mundo!", "I'm in Mexico City!");
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);*/
}
public void onLocationChanged(Location location) {
if (location != null) {
lat = location.getLatitude();
lng = location.getLongitude();
p = new GeoPoint((int) (lat * 1000000), (int) (lng * 1000000));
mc.animateTo(p);
//Log.d("LOCATION CHANGED", location.getLatitude() + "");
//Log.d("LOCATION CHANGED", location.getLongitude() + "");*/
Toast.makeText(HelloGoogleMaps.this,
location.getLatitude() + "" + location.getLongitude(),
Toast.LENGTH_LONG).show();
}
}
//makeUseOfNewLocation(location);
public void onProviderDisabled(String provider) {
}
public void onProviderEnabled(String provider) {
}
public void onStatusChanged(String provider, int status, Bundle extras) {
}
protected boolean isRouteDisplayed() {
return true;
}
class MyLocationOverlay extends com.google.android.maps.Overlay {
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
super.draw(canvas, mapView, shadow);
Paint paint = new Paint();
// Converts lat/lng-Point to OUR coordinates on the screen.
Point myScreenCoords = new Point();
mapView.getProjection().toPixels(p, myScreenCoords);
paint.setStrokeWidth(1);
paint.setARGB(255, 255, 255, 255);
paint.setStyle(Paint.Style.STROKE);
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.icon);
canvas.drawBitmap(bmp, myScreenCoords.x, myScreenCoords.y, paint);
canvas.drawText("Here I am...", myScreenCoords.x, myScreenCoords.y, paint);
return true;
} }
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.favmapview);
listbtn = (Button)findViewById(R.id.button1);
mapbtn = (Button)findViewById(R.id.button2);
TextView tv = (TextView)findViewById(R.id.tvmap);
bundle = getIntent().getExtras();
str1= bundle.getString("key");
lat = bundle.getStringArrayList("lat");
log=bundle.getStringArrayList("log");
location = bundle.getStringArrayList("location");
tv.setText(str1);
listbtn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
OpenListView(); // Function called to display list view
}
});
initialiseMapView();
}
// Navigates to listView class and displays listView
protected void OpenListView() {
final ProgressDialog dialog = ProgressDialog.show(FavMapView.this, "HIV ATLAS",
"Please wait...", true);
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
dialog.dismiss();
}
};
Thread checkUpdate = new Thread() {
public void run() {
Intent intent = new Intent(FavMapView.this,Favorites.class);
intent.putExtra("key", bundle.getString("key"));
startActivity(intent);
dialog.dismiss();
handler.sendEmptyMessage(0);
}
};
checkUpdate.start();
}
//============End
#Override
public boolean isRouteDisplayed() {
return true;
}
//Generates Map View
private void initialiseMapView() {
mapView = (MapView) findViewById(R.id.mapview);
mapController = mapView.getController();
mapView.setBuiltInZoomControls(true);
mapView.setSatellite(false);
GeoPoint startPoint = new GeoPoint((int)(40.7575 * 1E6), (int)(-73.9785 * 1E6));
mapController.setCenter(startPoint);
}
//===============End
#Override
public void onStart() {
super.onStart();
initialiseOverlays();
}
// Sets Geo points on Map View
private void initialiseOverlays() {
try {
// Create an ItemizedOverlay to display a list of markers
Drawable defaultMarker = getResources().getDrawable(R.drawable.marker);
placesItemizedOverlay = new HelloItemizedOverlay (FavMapView.this, defaultMarker);
for(int i=0;i<log.size();i++)
{
double lat1 = Double.parseDouble(lat.get(i));
double log1 =Double.parseDouble(log.get(i));
placesItemizedOverlay.addOverlayItem(new OverlayItem(new GeoPoint((int)(lat1 * 1E6),
(int) (log1 * 1E6)),location.get(i),null));
}
//==============================End
// Add the overlays to the map
mapView.getOverlays().add(placesItemizedOverlay);
} catch (NumberFormatException e) {
Toast.makeText(getApplicationContext(), "No Jobs available",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NotFoundException e) {
Toast.makeText(getApplicationContext(), "No Jobs available",
Toast.LENGTH_SHORT).show();
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Categories

Resources