I am trying to add some MapOverlays to my MapView and I get the following Error:
java.util.ConcurrentModificationException
at java.util.ArrayList$ArrayListIterator.next(ArrayList.java:569)
at com.google.android.maps.OverlayBundle.draw(OverlayBundle.java:44)
at com.google.android.maps.MapView.onDraw(MapView.java:530)
at android.view.View.draw(View.java:13458)
...
at dalvik.system.NativeStart.main(Native Method)
This is my doInBackground() method of my AsyncTask:
Drawable marker = myContext.getResources().getDrawable(
R.drawable.marker);
Bitmap bitmap = ((BitmapDrawable) marker).getBitmap();
Drawable marker_new = new BitmapDrawable(myContext.getResources(),
Bitmap.createScaledBitmap(
bitmap, MainActivity.MARKER_SIZE * 10,
MainActivity.MARKER_SIZE * 10, true));
mapOverlays = map.getOverlays();
int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLon = Integer.MAX_VALUE;
int maxLon = Integer.MIN_VALUE;
double fitFactor = 1.1;
MainActivity.mapListAddress.clear();
MainActivity.mapListTitle.clear();
MainActivity.mapListLati.clear();
MainActivity.mapListLongi.clear();
MainActivity.parseMaps();
for (int i = 0; i < MainActivity.mapListAddress.size(); i++) {
// String pointAddress = MainActivity.mapListAddress.get(i);
String pointTitel = MainActivity.mapListTitle.get(i);
MyItemizedOverlay itemizedOverlay = new MyItemizedOverlay(
marker_new, map);
double latitude = MainActivity.mapListLati.get(i) * 1e6;
double longitude = MainActivity.mapListLongi.get(i) * 1e6;
Geocoder geocoder;
List<Address> addresses = null;
geocoder = new Geocoder(Map.this, Locale.getDefault());
try {
addresses = geocoder.getFromLocation(MainActivity.mapListLati.get(i),
MainActivity.mapListLongi.get(i), 1);
} catch (IOException e) {
e.printStackTrace();
}
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getAddressLine(1);
String country = addresses.get(0).getAddressLine(2);
String pointAddress = address + "\n" + city + "\n" + country;
GeoPoint p = new GeoPoint((int) latitude, (int) longitude);
overlayitem = new OverlayItem(p, pointTitel,
pointAddress);
itemizedOverlay.setBalloonBottomOffset(40);
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
int lat = p.getLatitudeE6();
int lon = p.getLongitudeE6();
maxLat = Math.max(lat, maxLat);
minLat = Math.min(lat, minLat);
maxLon = Math.max(lon, maxLon);
minLon = Math.min(lon, minLon);
map.getController().zoomToSpan((int) (Math.abs(maxLat - minLat) * fitFactor),
(int) (Math.abs(maxLon - minLon) * fitFactor));
map.getController().animateTo(new GeoPoint((maxLat + minLat) / 2,
(maxLon + minLon) / 2));
}
return null;
Why does this error occur and what am I doing wrong in my code?
Try to synchronize the mapOverlays.add(itemizedOverlay);. I think this is where the issue is, multiple threads trying to add at the same time.
Related
I followed the example here: How to set screen zoom by geopoints?
But my problem is that my route is very small in the mapview. It should end near the borders.
This is how it looks with the code below:
private void centerMap(ArrayList<GeoPoint> waypoints) {
GeoPoint[] geoPoints = new GeoPoint[waypoints.size()];
for(int i = 0; i<waypoints.size(); i++) {
geoPoints[i] = waypoints.get(i);
}
int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLon = Integer.MAX_VALUE;
int maxLon = Integer.MIN_VALUE;
//for (Point point : twoPoints) {
for(GeoPoint point: geoPoints){
int lat = (int) (point.getLatitude() * 1E6);
int lon = (int) (point.getLongitude() * 1E6);
maxLat = Math.max(lat, maxLat);
minLat = Math.min(lat, minLat);
maxLon = Math.max(lon, maxLon);
minLon = Math.min(lon, minLon);
}
mapView.getController().zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
mapView.getController().setCenter(new GeoPoint((maxLat + minLat) / 2, (maxLon + minLon) / 2));
}
private void centerMap(ArrayList<GeoPoint> waypoints) {
BoundingBox bb = BoundingBox.fromGeoPoints(waypoints);
mapView.zoomToBoundingBox(bb);
}
And note that lat/lon values are now double by default in osmdroid.
I am experimenting using nutiteq , as i found it a better alternative working on 3d maps.I want to learn every bit of it.So I am making a simple project where I can calculate the speed distance and time from its current location simultaneously on its tracking.
I applied some logics but failed.Can any of you help me.
public final static double AVERAGE_RADIUS_OF_EARTH = 6371;
public int calculateDistance(double userLat, double userLng, double venueLat, double venueLng) {
double latDistance = Math.toRadians(userLat - venueLat);
double lngDistance = Math.toRadians(userLng - venueLng);
double a = (Math.sin(latDistance / 2) * Math.sin(latDistance / 2)) +
(Math.cos(Math.toRadians(userLat))) *
(Math.cos(Math.toRadians(venueLat))) *
(Math.sin(lngDistance / 2)) *
(Math.sin(lngDistance / 2));
double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
return (int) (Math.round(AVERAGE_RADIUS_OF_EARTH * c));
}
This is what I have used so far and is calling this function onLocationChange.
Please help. Thanks in advance
This is my code and is working well:
case R.id.btn_StartTrack:
location_manager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
provider = location_manager.getBestProvider(criteria, false);
//location.getAccuracy();
if (location_manager.isProviderEnabled(LocationManager.GPS_PROVIDER))
{
if (!isclickedBtnStartTrackFirstTym)
{
for (int i = 0; i < geoLayerList.size(); i++)
{
mapView.getLayers().removeLayer(geoLayerList.get(i));
}
for (int i = 0; i < markerlist.size(); i++)
{
mapView.getLayers().removeLayer(markerlist.get(i));
}
for (int i = 0; i < markerlist1.size(); i++)
{
mapView.getLayers().removeLayer(markerlist1.get(i));
}
geoLayerList = new ArrayList<GeometryLayer>();
geoLayerList.clear();
markerlist = new ArrayList<MarkerLayer>();
markerlist.clear();
markerlist1 = new ArrayList<MarkerLayer>();
markerlist1.clear();
journeyDuration = 0;
totalSpeed = 0.0;
averageSpeed = 0.0;
distanceInMiles = 0.0;
distanceInMilesRound=0.0;
mtvCalcTime.setText("00:00");
mtvCalcDistance.setText("0:00");
mtvCalcSpeed.setText("0.0");
isclickedBtnStartTrackFirstTym = true;
btn_startTrack.setBackgroundResource(R.drawable.stop_tracking);
java.util.Date date = new java.util.Date();
journey_id = String.valueOf(date.getTime());
location_manager.requestLocationUpdates(provider, 1000, 1, activity);
startJourneyTimer();
}
else
{
location_manager.removeUpdates(activity);
if (!arr_lat_long.isEmpty())
{
last_pos = arr_lat_long.get(arr_lat_long.size() - 1);
Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.pointer);
MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setAllowOverlap(false).setColor(Color.WHITE).build();
Label markerLabel = new DefaultLabel("");
markerLayer1 = new MarkerLayer(mapView.getComponents().layers.getBaseProjection());
Marker marker = new Marker(last_pos, markerLabel, markerStyle, null);
markerLayer1.add(marker);
markerlist.add(markerLayer1);
mapView.getLayers().addLayer(markerLayer1);
}
btn_startTrack.setBackgroundResource(R.drawable.start_tracking);
mLinearLayout.setVisibility(View.GONE);
mlinbtns.setVisibility(View.VISIBLE);
layoutVisibility = "2";
isclickedBtnStartTrackFirstTym = false;
if (timer != null)
{
timer.cancel();
}
}
}
else
{
Utilities.buildAlertMessageNoGps(getActivity());
}
break;
}
/**
*
* onLoctionChanged
*/
#Override
public void onLocationChanged(Location location)
{
double accuracy = location.getAccuracy();
if(accuracy<=30)
{
Tripname = "tripname";
Double newLat = location.getLatitude();
Double newLong = location.getLongitude();
lat_current = location.getLatitude();
lng_current = location.getLongitude();
if (endLatitude == -180)
{
endLatitude = newLat;
endLongitude = newLong;
}
else
{
startLatitude = endLatitude;
startLongitude = endLongitude;
endLatitude = newLat;
endLongitude = newLong;
}
double speed = (double) location.getSpeed();
speedInmph = JourneyUtils.getSpeedInMiles(speed); // method for speed t mph and kmph
totalSpeed = averageSpeed + speedInmph;
averageSpeed = totalSpeed / 2;
averageSpeed = Utilities.roundTwoDecimals(averageSpeed);
mtvCalcSpeed.setText(averageSpeed + "");
if (startLatitude != -180)
{
double distance = JourneyUtils.getDistanceInMiles(startLatitude, startLongitude, endLatitude, endLongitude);
distanceInMiles = distance + distanceInMiles;
distanceInMilesRound = Utilities.roundTwoDecimals(distanceInMiles);
mtvCalcDistance.setText(distanceInMilesRound + "");
}
long newTimeInMillis = location.getTime();
String utcDateTime = Utilities.getUTCDateTimeFromMillis(newTimeInMillis);
//mtvCalcTime.setText(utcDateTime);
db_journeySave.insertjourney(journey_id, utcDateTime, newLat + "", newLong + "", distanceInMiles + "", speedInmph + "", accuracy + "", Tripname, 0, 0, localTime1 + ":00");
mapView.getCameraPos();
MapPos lineLocation = mapView.getLayers().getBaseProjection().fromWgs84(endLongitude, endLatitude);
arr_lat_long.add(lineLocation);
ArrayList<MarkerLayer> arr_markerlist = new ArrayList<MarkerLayer>();
if (arr_lat_long.size() > 1)
{
MapPos start_lat = arr_lat_long.get(0);
Bitmap pointMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.green_pointer);
MarkerStyle markerStyle = MarkerStyle.builder().setBitmap(pointMarker).setSize(0.5f).setAllowOverlap(false).setColor(Color.WHITE).build();
Label markerLabel = new DefaultLabel("");
MarkerLayer markerLayer = new MarkerLayer(mapView.getComponents().layers.getBaseProjection());
Marker marker = new Marker(start_lat, markerLabel, markerStyle, null);
markerLayer.add(marker);
markerlist.add(markerLayer);
mapView.getLayers().addLayer(markerLayer);
MapPos last_pos1 = arr_lat_long.get(arr_lat_long.size() - 1);
Bitmap movingMarker = UnscaledBitmapLoader.decodeResource(getResources(), R.drawable.blue);
MarkerStyle markerStyle1 = MarkerStyle.builder().setBitmap(movingMarker).setSize(0.5f).setAllowOverlap(false).setColor(Color.WHITE).build();
Label markerLabel1 = new DefaultLabel("");
MarkerLayer markerLayer1 = new MarkerLayer(mapView.getComponents().layers.getBaseProjection());
Marker marker1 = new Marker(last_pos1, markerLabel1, markerStyle1, null);
markerLayer1.add(marker1);
mapView.getLayers().addLayer(markerLayer1);
arr_markerlist.add(markerLayer1);
if(arr_markerlist.size()>0)
{
markerLayer1.remove(marker1);
mapView.getLayers().removeLayer(markerLayer1);
}
geoLayer = new GeometryLayer(mapView.getComponents().layers.getBaseProjection());
mapView.getLayers().addLayer(geoLayer);
geoLayerList.add(geoLayer);
StyleSet<LineStyle> lineStyleSet = new StyleSet<LineStyle>(LineStyle.builder().setWidth(0.15f).setColor(Color.CYAN).build());
ArrayList<MapPos> arr1_lat_long = new ArrayList<MapPos>();
arr1_lat_long.add(arr_lat_long.get(arr_lat_long.size() - 2));
arr1_lat_long.add(arr_lat_long.get(arr_lat_long.size() - 1));
line = new Line(arr1_lat_long, null, lineStyleSet, null);
geoLayer.add(line);
}
}
else
{
}
}
i want to display my location and destination location at map. the problem is that the destination location always point at same location even if i change another destination long and lat...
here is the code
protected void tampilkanPosisikeMap(Location newLocation) {
List<Overlay> overlays = mapView.getOverlays();
if (overlays.size() > 0) {
for (Iterator iterator = overlays.iterator(); iterator.hasNext();) {
iterator.next();
iterator.remove();
}
}
GeoPoint geopoint = new GeoPoint(
(int) (newLocation.getLatitude() * 1E6), (int) (newLocation
.getLongitude() * 1E6));
GeoPoint myposition = geopoint;
Location locationA = new Location("point A");
Location locationB = new Location("point B");
locationA.setLatitude(geopoint.getLatitudeE6() / 1E6);
locationA.setLongitude(geopoint.getLongitudeE6() / 1E6);
Drawable icon1 = getResources().getDrawable(R.drawable.user);
icon1.setBounds(0, 0, icon1.getIntrinsicWidth(), icon1
.getIntrinsicHeight());
MyItemizedOverlay overlay1 = new MyItemizedOverlay(icon1, this);
OverlayItem item1 = new OverlayItem(geopoint, "Posisi Anda", "Lat:"
+ locationA.getLatitude() + "\nLng:" + locationA.getLongitude());
overlay1.addItem(item1);
mapView.getOverlays().add(overlay1);
String lat2,longi2;
String nama_rs;String alamat_rs;
nama_rs = getIntent().getExtras().getString("namarsakit");
alamat_rs = getIntent().getExtras().getString("alamatrsakit");
lat2 = getIntent().getExtras().getString("lat");
longi2 = getIntent().getExtras().getString("longi");
Double lintang_rs = Double.parseDouble(lat2);
Double bujur_rs = Double.parseDouble(longi2);
GeoPoint geopoint1 = new GeoPoint(
(int) (lintang_rs * 1E6),
(int) (bujur_rs * 1E6));
locationB.setLatitude(geopoint1.getLatitudeE6() / 1E6);
locationB.setLongitude(geopoint1.getLongitudeE6() / 1E6);
DecimalFormat formatData = new DecimalFormat("#.#");
float distance = (float) locationA.distanceTo(locationB) / 1000;
String jarak;
jarak = String.valueOf(formatData.format(distance));
Drawable icon = getResources().getDrawable(R.drawable.marker); //
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
MyItemizedOverlay overlay = new MyItemizedOverlay(icon, this); //
OverlayItem item = new OverlayItem(geopoint1, nama_rs, //
alamat_rs
+ "\n\nJarak dari Posisi Anda : " + jarak + " km");
overlay.addItem(item);
mapView.getOverlays().add(overlay);
Toast.makeText(MapDetailActivity.this,"nama = "+nama_rs+"lat tujuan= "+lintang_rs+"long tujuan = "+bujur_rs, Toast.LENGTH_SHORT).show();
mapView.getController().animateTo(geopoint1);
}
this is the destination code from above :
String lat2,longi2;
String nama_rs;String alamat_rs;
nama_rs = getIntent().getExtras().getString("namarsakit");
alamat_rs = getIntent().getExtras().getString("alamatrsakit");
lat2 = getIntent().getExtras().getString("lat");
longi2 = getIntent().getExtras().getString("longi");
Double lintang_rs = Double.parseDouble(lat2);
Double bujur_rs = Double.parseDouble(longi2);
GeoPoint geopoint1 = new GeoPoint(
(int) (lintang_rs * 1E6),
(int) (bujur_rs * 1E6));
locationB.setLatitude(geopoint1.getLatitudeE6() / 1E6);
locationB.setLongitude(geopoint1.getLongitudeE6() / 1E6);
DecimalFormat formatData = new DecimalFormat("#.#");
float distance = (float) locationA.distanceTo(locationB) / 1000;
String jarak;
jarak = String.valueOf(formatData.format(distance));
Drawable icon = getResources().getDrawable(R.drawable.marker); //
icon.setBounds(0, 0, icon.getIntrinsicWidth(), icon
.getIntrinsicHeight());
MyItemizedOverlay overlay = new MyItemizedOverlay(icon, this); //
OverlayItem item = new OverlayItem(geopoint1, nama_rs, //
alamat_rs
+ "\n\nJarak dari Posisi Anda : " + jarak + " km");
overlay.addItem(item);
mapView.getOverlays().add(overlay);
Toast.makeText(MapDetailActivity.this,"nama = "+nama_rs+"lat tujuan= "+lintang_rs+"long tujuan = "+bujur_rs, Toast.LENGTH_SHORT).show();
mapView.getController().animateTo(geopoint1);
For You to be able to show your Current location you must tap on to GPS location provider or Network Location provider. Looking at your code I cannot see any of this. Please note on emulator DDMS will default to a specific location. unless you supply one yourself
I have heard that KML file is no longer available since 27 July 2012 (because Google has changed the structure of retrieving Google Directions, now you can only get it by JSON or XML)
So plz guide me how to make road route between 2 location.
BELOW CODE IS WORKING FINE NW ENJOY GUYS
This is my code:
I refered this link : http://www.androidhive.info/2012/08/android-working-with-google-places-and-maps-tutorial/
PlacesMapActivity.java
In below code it is showing straight line between 2 point.
public class PlacesMapActivity extends MapActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.map_places);
Intent i = getIntent(); // Getting intent data
String user_latitude = i.getStringExtra("user_latitude");// Users current geo location
String user_longitude = i.getStringExtra("user_longitude");//Userscurrent geo location
nearPlaces = (PlacesList) i.getSerializableExtra("near_places");// Nearplaces list
mapView = (MapView) findViewById(R.id.mapView);
mapView.setBuiltInZoomControls(true);
mapOverlays = mapView.getOverlays();
geoPoint = new GeoPoint((int) (Double.parseDouble(user_latitude) * 1E6), (int) (Double.parseDouble(user_longitude) * 1E6));// Geopoint to place on map
geoPoint1 = new GeoPoint((int) (Double.parseDouble("12.930621") * 1E6),
(int) (Double.parseDouble("77.581710") * 1E6));//Geopoint to Clientplace on map
Drawable drawable_user = this.getResources()
.getDrawable(R.drawable.mark_red); // Drawable marker icon
Drawable drawable_client = this.getResources()
.getDrawable(R.drawable.mark_blue); // Drawable Client icon
Drawable drawable = this.getResources()
.getDrawable(R.drawable.clientflag); // Drawable marker icon
// Map overlay item
itemizedOverlay = new AddItemizedOverlay(drawable_user, this);
overlayitem = new OverlayItem(geoPoint, "Your Location","That is you!");
itemizedOverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedOverlay);
itemizedOverlay.populateNow();
// Map client overlay item
itemizedOverlay1 = new AddItemizedOverlay(drawable_client, this);
overlayitem1 = new OverlayItem(geoPoint1, "Your Location2", "I am ur client!");
itemizedOverlay1.addOverlay(overlayitem1);
mapOverlays.add(itemizedOverlay1);
itemizedOverlay1.populateNow();
// Map client overlay item
itemizedOverlay = new AddItemizedOverlay(drawable, this);
mc = mapView.getController();
// These values are used to get map boundary area
// The area where you can see all the markers on screen
int minLat = Integer.MAX_VALUE;
int minLong = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int maxLong = Integer.MIN_VALUE;
// check for null in case it is null
if (nearPlaces.results != null) {
// loop through all the places
for (Place place : nearPlaces.results) {
latitude = place.geometry.location.lat; // latitude
longitude = place.geometry.location.lng; // longitude
// Geopoint to place on map
geoPoin = new GeoPoint((int) (latitude * 1E6),
(int) (longitude * 1E6));
// Map overlay item
overlayitem = new OverlayItem(geoPoin, place.name,
place.vicinity);
itemizedOverlay.addOverlay(overlayitem);
// calculating map boundary area
minLat = (int) Math.min( geoPoin.getLatitudeE6(), minLat );
minLong = (int) Math.min( geoPoin.getLongitudeE6(), minLong);
maxLat = (int) Math.max( geoPoin.getLatitudeE6(), maxLat );
maxLong = (int) Math.max( geoPoin.getLongitudeE6(), maxLong );
}
mapOverlays.add(itemizedOverlay);
// showing all overlay items
itemizedOverlay.populateNow();
}
// Adjusting the zoom level so that you can see all the markers on map
mapView.getController().zoomToSpan(Math.abs( minLat - maxLat ), Math.abs( minLong - maxLong ));
// Showing the center of the map
mc.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLong + minLong)/2 ));
mc.animateTo(geoPoint1);
//mapView.postInvalidate();
myoverlay = new MyOverlay();
mapOverlays.add(myoverlay);
}
#Override
public boolean onCreateOptionsMenu(Menu menu)
{
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.menu.activity_main, menu);
return true;
}
/**
* Event Handling for Individual menu item selected
* Identify single menu item by it's id
* */
#Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case R.id.mylocation:
// Single menu item is selected do something
Toast.makeText(PlacesMapActivity.this, "Moving To Current location", Toast.LENGTH_SHORT).show();
// geoPoint.gpsCurrentLocation();
return true;
case R.id.mapStreet:
Toast.makeText(PlacesMapActivity.this, "Map Normal Street View", Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==true){
mapView.setSatellite(false);
}
return true;
case R.id.mapSatellite:
Toast.makeText(PlacesMapActivity.this, "Map Satellite View", Toast.LENGTH_SHORT).show();
if(mapView.isSatellite()==false){
mapView.setSatellite(true);
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected boolean isRouteDisplayed() {
return false;
}
add this road route
private void DrawPath(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch, int green, MapView mMapView) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(makeUrl(scrgeoPoint, destgeoPoint, destgeopointsearch));
HttpResponse response;
try {
response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream is = null;
is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
sb.append(reader.readLine() + "\n");
String line = "0";
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
reader.close();
String result = sb.toString();
JSONObject jsonObject = new JSONObject(result);
JSONArray routeArray = jsonObject.getJSONArray("routes");
JSONObject routes = routeArray.getJSONObject(0);
JSONObject overviewPolylines = routes.getJSONObject("overview_polyline");
String encodedString = overviewPolylines.getString("points");
List<GeoPoint> pointToDraw = decodePoly(encodedString);
mMapView.getOverlays().add(new MyOverLay(pointToDraw));
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
private List<GeoPoint> decodePoly(String encoded) {
List<GeoPoint> poly = new ArrayList<GeoPoint>();
int index = 0, len = encoded.length();
int lat = 0, lng = 0;
while (index < len) {
int b, shift = 0, result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlat = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lat += dlat;
shift = 0;
result = 0;
do {
b = encoded.charAt(index++) - 63;
result |= (b & 0x1f) << shift;
shift += 5;
} while (b >= 0x20);
int dlng = ((result & 1) != 0 ? ~(result >> 1) : (result >> 1));
lng += dlng;
GeoPoint p = new GeoPoint((int) (((double) lat / 1E5) * 1E6),
(int) (((double) lng / 1E5) * 1E6));
poly.add(p);
}
return poly;
}
private String makeUrl(GeoPoint scrgeoPoint, GeoPoint destgeoPoint, GeoPoint destgeopointsearch) {
StringBuilder urlString = new StringBuilder();
urlString.append("http://maps.googleapis.com/maps/api/directions/json");
urlString.append("?origin=");// from
urlString.append(Double.toString((double) scrgeoPoint.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) scrgeoPoint.getLongitudeE6() / 1.0E6));
urlString.append("&destination=");// to
urlString.append(Double.toString((double) destgeoPoint.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) destgeoPoint.getLongitudeE6() / 1.0E6));
/* urlString.append("&destination=");// searchto
urlString.append(Double.toString((double) destgeopointsearch.getLatitudeE6() / 1.0E6));
urlString.append(",");
urlString.append(Double.toString((double) destgeopointsearch.getLongitudeE6() / 1.0E6));
*/
urlString.append("&sensor=false");
Log.d("xxx", "URL=" + urlString.toString());
return urlString.toString();
}
At Last i got road route map between two point.. Add this code.
class MyOverLay extends Overlay {
private int pathColor;
private final List<GeoPoint> points;
private boolean drawStartEnd;
public MyOverLay(List<GeoPoint> pointToDraw) {
this(pointToDraw, Color.MAGENTA, true);
}
public MyOverLay(List<GeoPoint> points, int pathColor, boolean drawStartEnd) {
this.points = points;
this.pathColor = pathColor;
this.drawStartEnd = drawStartEnd;
}
private void drawOval(Canvas canvas, Paint paint, Point point) {
Paint ovalPaint = new Paint(paint);
ovalPaint.setStyle(Paint.Style.FILL_AND_STROKE);
ovalPaint.setStrokeWidth(2);
ovalPaint.setColor(Color.BLUE);
int _radius = 6;
RectF oval = new RectF(point.x - _radius, point.y - _radius,
point.x + _radius, point.y + _radius);
canvas.drawOval(oval, ovalPaint);
}
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false && points != null) {
Point startPoint = null, endPoint = null;
Path path = new Path();
// We are creating the path
for (int i = 0; i < points.size(); i++) {
GeoPoint gPointA = points.get(i);
Point pointA = new Point();
projection.toPixels(gPointA, pointA);
if (i == 0) { // This is the start point
startPoint = pointA;
path.moveTo(pointA.x, pointA.y);
} else {
if (i == points.size() - 1)// This is the end point
endPoint = pointA;
path.lineTo(pointA.x, pointA.y);
}
}
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(pathColor);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(5);
paint.setAlpha(90);
if (getDrawStartEnd()) {
if (startPoint != null) {
drawOval(canvas, paint, startPoint);
}
if (endPoint != null) {
drawOval(canvas, paint, endPoint);
}
}
if (!path.isEmpty())
canvas.drawPath(path, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
public boolean getDrawStartEnd() {
return drawStartEnd;
}
public void setDrawStartEnd(boolean markStartEnd) {
drawStartEnd = markStartEnd;
}
}
}
You can see my post here with full answer on how to do it in JSON since Google shut down KML.
I have an array of latitude and longitude points. I use them to make markers on the map. What can I do to show all of the markers on the map at the same time. eg make a good fit so that if the markers are within a city I zoom it in to only show the city and not the whole state, country etc...
Thanks
something like this might help
private void centerGroup(int groupId){
if(groupId>0){
int minLat = Integer.MAX_VALUE;
int maxLat = Integer.MIN_VALUE;
int minLon = Integer.MAX_VALUE;
int maxLon = Integer.MIN_VALUE;
Cursor cursor = getYourLantLongs(groupId);
if (cursor.moveToFirst()){
final int LAT_INDEX = cursor.getColumnIndex(T.Waypoints.LATITUDE);
final int LON_INDEX = cursor.getColumnIndex(T.Waypoints.LONGITUDE);
do {
final int lat = (int) (cursor.getFloat(LAT_INDEX)*1E6);
final int lon = (int) (cursor.getFloat(LON_INDEX)*1E6);
maxLat = Math.max(lat, maxLat);
minLat = Math.min(lat, minLat);
maxLon = Math.max(lon, maxLon);
minLon = Math.min(lon, minLon);
} while(cursor.moveToNext());
mapController.zoomToSpan(Math.abs(maxLat - minLat), Math.abs(maxLon - minLon));
mapController.animateTo(new GeoPoint((maxLat + minLat)/2, (maxLon + minLon)/2 ));
/*
final int cLat = (int)((maxLat*1E6 + minLat*1E6)/2);
final int cLon = (int)((maxLon*1E6 + minLon*1E6)/2);
final int zLat = (int)Math.abs(maxLat - minLat);
final int zLon = (int)Math.abs(maxLon - minLon);
//mapController.zoomToSpan(zLat, zLon);
mapController.animateTo(new GeoPoint(cLat, cLon));
*/
}
}
}
in short you make a square and zoom in.
Go through your array and save min and max values of latitude and longitude.
Then use
mMapController.zoomToSpan((maxLatitude - minLatitude), (maxLongitude - minLongitude));
to get the right zoom level. And
mMapController.animateTo(new GeoPoint(
(maxLatitude + minLatitude)/2 ,
(maxLongitude + minLongitude)/2 ));
to move the map to the center of your markers.
Have fun!