Draw the route between 2 overlays - android

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.

Related

Map overlay not updating

i am trying to draw the path as the farmer moves around his farm the below are my classes ,my problem is when i start tracing the line moves even when the user is not moving and path is not updating as he moves
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
mainactivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}
Can you confirm that you're always using the GPS to trace the route? Otherwise you might get incorrect results and your patch might get drawn like on Apple maps. For those cases always try using the GPS, I'm sure you don't want incorrect path to be drawn on the map. The network provider can triangulate a relative point on the map, but it will be incorrect 99% of the time in this case, because the position is relative.
Cheers

Overlay not drawing on the right spot

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();
}`

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

if i want to add overlay items on map using gps

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

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