Android google maps show geo points which are closest to current location - android

Is there any way If I have like 100 geo points added in my MapActivity and I want to show only these which are like 1000m away from my current location. The other ones should not be visible on the map.
Any suggestions?

Ok, here is the example. You can subclass Overlay class and override draw method. Whenever the Overlay is invalidated, you should check if your points are within 1000m from your location. Off course, you should know your location within your overlay class. The flowing is the example:
public class MyMapOverlay extends Overlay {
Bitmap bmp;
Context context;
public MyMapOverlay()
{
bmp = BitmapFactory.decodeResource(MyApplication.getContext().getResources(), R.drawable.myplace);
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
for(int i = 0;i<points.size(); i++)
{
GeoPoint point = points.get(i);
Location locationA = new Location("point " + String.valueOf(i));
locationA.setLatitude(point.getLatitudeE6());
locationA.setLongitude(point.getLongitudeE6());
float distance = myLocation.distanceTo(locationA);
if(distance < 1000.0)
{
mapView.getProjection().toPixels(p, screenPts);
canvas.drawBitmap(bmp, screenPts.x-bmp.getWidth()/2, screenPts.y-bmp.getHeight(), null);
}
}
return true;
}

With some help of the first answer I find this solution :
if(location != null){
Location locA = new Location("gps");
GeoPoint myLoc = new GeoPoint((int)(location.getLatitude() * 1E6), (int)(location.getLongitude() * 1E6));
mapController.animateTo(myLoc);
String sqlbars = "SELECT DISTINCT id, latitude, longitude, address, " +
" (SELECT category FROM bars_categories WHERE bar_id=bars.id) AS category " +
" FROM bars WHERE is_active=1";
Cursor curBars = dbHelper.executeSQLQuery(sqlbars);
if(curBars != null){
if(curBars.getCount() > 0){
for(curBars.move(0);curBars.moveToNext();curBars.isAfterLast()){
double latitude = curBars.getDouble(curBars.getColumnIndex("latitude"));
double longitude = curBars.getDouble(curBars.getColumnIndex("longitude"));
final List<Overlay> mapOverlays = mapView.getOverlays();
Drawable drawable = SofiaLiveNearbyActivity.this.getResources().getDrawable(R.drawable.pin_map_icon);
int markerWidth = drawable.getIntrinsicWidth();
int markerHeight = drawable.getIntrinsicHeight();
drawable.setBounds(0, markerHeight, markerWidth, 0);
final HelloItemizedOverlay itemizedoverlay = new HelloItemizedOverlay(drawable, SofiaLiveNearbyActivity.this);
GeoPoint point = new GeoPoint((int)(latitude * 1E6),(int)(longitude *1E6));
OverlayItem overlayitem = new OverlayItem(point, "Type: "+category+"\n----------------\nAddress: "+address, id);
locA.setLatitude(latitude);
locA.setLongitude(longitude);
float distance = location.distanceTo(locA);
if(distance < 1000.0){
itemizedoverlay.addOverlay(overlayitem);
mapOverlays.add(itemizedoverlay);
}
}
}
curBars.close();
}
and it worked.

Related

Location change and put Marker on Click in openstreetmap

I am new to Open Street Map map. I want to put the marker on map where i Tapped. I want to delete previous marker also. Please help me.
Thanks in advance. Here is my code
Overlay touchOverlay = new Overlay(this) {
ItemizedIconOverlay<OverlayItem> anotherItemizedIconOverlay = null;
#Override
protected void draw(Canvas arg0, MapView arg1, boolean arg2) {
}
#Override
public boolean onSingleTapConfirmed(final MotionEvent e,
final MapView mapView) {
Projection proj = mapView.getProjection();
GeoPoint loc = (GeoPoint) proj.fromPixels((int) e.getX(),
(int) e.getY());
String longitude = Double
.toString(((double) loc.getLongitudeE6()) / 1000000);
String latitude = Double
.toString(((double) loc.getLatitudeE6()) / 1000000);
ArrayList<OverlayItem> overlayArray = new ArrayList<OverlayItem>();
OverlayItem mapItem = new OverlayItem("", "", new GeoPoint(
(((double) loc.getLatitudeE6()) / 1000000),
(((double) loc.getLongitudeE6()) / 1000000)));
Drawable marker = null;
mapItem.setMarker(marker);
overlayArray.add(mapItem);
if (anotherItemizedIconOverlay == null) {
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(
getApplicationContext(), overlayArray, null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
mapView.invalidate();
} else {
mapView.getOverlays().remove(anotherItemizedIconOverlay);
mapView.invalidate();
anotherItemizedIconOverlay = new ItemizedIconOverlay<OverlayItem>(
getApplicationContext(), overlayArray, null);
mapView.getOverlays().add(anotherItemizedIconOverlay);
}
return true;
}
};
Finally i get solution of this problem. here is my answer.
#Override
public boolean onSingleTapConfirmed(MotionEvent e, MapView mapView) {
Projection proj = mapView.getProjection();
p = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
proj = mapView.getProjection();
loc = (GeoPoint) proj.fromPixels((int) e.getX(), (int) e.getY());
String longitude = Double
.toString(((double) loc.getLongitudeE6()) / 1000000);
String latitude = Double
.toString(((double) loc.getLatitudeE6()) / 1000000);
Toast toast = Toast.makeText(getApplicationContext(),
"Longitude: "
+ longitude + " Latitude: " + latitude, Toast.LENGTH_SHORT);
toast.show();
return true;
}
private void addLocation(double lat, double lng) {
// ---Add a location marker---
p = new GeoPoint((int) (lat * 1E6), (int) (lng * 1E6));
Drawable marker = getResources().getDrawable(
android.R.drawable.star_big_on);
int markerWidth = marker.getIntrinsicWidth();
int markerHeight = marker.getIntrinsicHeight();
marker.setBounds(0, markerHeight, markerWidth, 0);
ResourceProxy resourceProxy = new DefaultResourceProxyImpl(
getApplicationContext());
myItemizedOverlay = new MyItemizedOverlay(marker, resourceProxy);
List<Overlay> listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(myItemizedOverlay);
mapView.invalidate();
}

How show multiple points on Google map?

When start Google Maps,I focus to a point on map as:
GeoPoint srcGeoPoint = new GeoPoint((int) (src_lat * 1E6), (int) (src_long * 1E6));
GeoPoint destGeoPoint = new GeoPoint((int) (dest_lat * 1E6), (int) (dest_long * 1E6));
DrawPath(srcGeoPoint, destGeoPoint, Color.BLUE, mapView);
mapView.getController().animateTo(destGeoPoint);
If I use mapView.getController().animateTo(destGeoPoint); the map only focuses to point destGeoPoint.
I want Map to show 2 points: srcGeoPoint and destGeoPoint when start Google Map.
This 2 point had draw on Map. I want to can see 2 point when map open.
Create your mapOverlay:
public class MapOverlay extends Overlay {
MapView mapView;
GeoPoint p;
private Context c;
public MapOverlay(Context c, MapView m, GeoPoint p){
this.c=c;
mapView=m;
this.p=p;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
//---translate the GeoPoint to screen pixels---
Point screenPts = new Point();
mapView.getProjection().toPixels(p, screenPts);
//---add the marker---
Bitmap bmp = BitmapFactory.decodeResource(c.getResources(), R.drawable.icon_notif);
canvas.drawBitmap(bmp, screenPts.x, screenPts.y-50, null);
return true;
}
}
This is a method that starts the map:
private void initMapa() {
try{
//If you want zoom controls
mapa.setBuiltInZoomControls(true);
GeoPoint loc;
Double lat;
Double long;
MapController controlMapa = mapa.getController();
controlMapa.setZoom(13); // de 1 a 21
mapa.setSatellite(true);
mapa.displayZoomControls(true);
// First point
ArrayList<GeoPoint> ap=new ArrayList<GeoPoint>();
latitud = (double) lat1 *1E6;
longitud = (double) long1 *1E6;
loc = new GeoPoint(latitud.intValue(), longitud.intValue());
controlMapa.animateTo(loc);
ap.add(loc);
// Second point
latitud = (double) fichaOtraPersona.getLoc_lan()*1E6;
longitud = (double) fichaOtraPersona.getLoc_lon()*1E6;
loc = new GeoPoint(latitud.intValue(), longitud.intValue());
ap.add(loc);
controlMapa.animateTo(loc);
addPointInTheMap(ap);
} catch (Exception e) {
showToast("Error");
}
}
And the addPointInTheMap method:
private void anadirPuntoEnMapa(ArrayList<GeoPoint> points){
//---Add a location marker---
List<Overlay> listOfOverlays = mapa.getOverlays();
listOfOverlays.clear();
Iterator<GeoPoint> it=points.iterator();
while (it.hasNext()){
MapOverlay mapOverlay = new MapOverlay(getApplicationContext(), mapa, it.next());
listOfOverlays.add(mapOverlay);
}
mapa.invalidate();
}
Try to read the Location and Map Applications Chapter from the Android Cookbook. The main idea is to add an inner class to your MapActivity which extends ItemizedOverlay and implement the abstract methods and the default constructor. The ItemizedOverlay uses your implementations of the createItem and size() methods to get hold of all the overlay items in your implementation and do the aggregation.

How to make anything when my geolocation is changed?

I want to make some action, i.e. show dialog with text 'im here' every time when my geolocation will be changed.
I'm using MyLocationOverlay to draw a dot on my location on the Google Maps's mapview.
How can I achieve that?
Below is the location listener class -
private MyOverLay draw = new MyOverLay();
class MyLocationListener_gps implements LocationListener {
public void onLocationChanged(Location location) {
clat = location.getLatitude();
clon = location.getLongitude();
GeoPoint geoPoint = new GeoPoint((int) (clat * 1E6),
(int) (clon * 1E6));
mapView.getController().animateTo(geoPoint);
draw = new MyOverLay(geoPoint);
mapView.getOverlays().add(draw);
}
}
Here is code overlay class-
class MyOverLay extends Overlay {
private GeoPoint gp1;
private int mRadius = 3;
public MyOverLay() {
}
public MyOverLay(GeoPoint gp1) {
this.gp1 = gp1;
}
#Override
public boolean draw(Canvas canvas, MapView mapView, boolean shadow,
long when) {
Projection projection = mapView.getProjection();
if (shadow == false) {
Paint paint = new Paint();
paint.setAntiAlias(true);
Point point = new Point();
projection.toPixels(gp1, point);
paint.setColor(Color.BLUE);
RectF oval = new RectF(point.x - mRadius, point.y - mRadius,
point.x + mRadius, point.y + mRadius);
canvas.drawOval(oval, paint);
}
return super.draw(canvas, mapView, shadow, when);
}
}
It will draw a blue dot as u move and ur co-ordinates chnage.
Override the onLocationChanged method:
// Create an overlay to show current location
mMyLocationOverlay = new MyLocationOverlay(this, mMapView) {
#Override
public void onLocationChanged(android.location.Location location) {
String text = "New coordinates: " + location.getLatitude() + ", " + location.getLatitude();
Toast toast = Toast.makeText(getApplicationContext(), text, Toast.LENGTH_SHORT);
toast.show();
super.onLocationChanged(location);
}
};
mMyLocationOverlay.runOnFirstFix(new Runnable() { public void run() {
mMapView.getController().animateTo(mMyLocationOverlay.getMyLocation());
}});
mMapView.getOverlays().add(mMyLocationOverlay);

Wrong distances when creating random locations

I am trying to create random locations nearby my location. What i want is to create random latitude/longitude pairs inside a 200 meters circle surrounding my location. After asking this question: generate random locations nearby my location this is what i have come up with.
in onLocationChanged, this is what i do:
private void updateWithNewLocation(Location location) {
if (location != null) {
this.myItemizedOverlay.clear();
this.nonPlayerItemizedOverlay.clear();
this.mapOverlays.clear();
// Update my map location.
Double latitude = location.getLatitude() * 1E6;
Double longitude = location.getLongitude() * 1E6;
GeoPoint geoPoint = new GeoPoint(latitude.intValue(),
longitude.intValue());
CustomOverlayItem pcOverlayItem = new CustomOverlayItem(geoPoint,
"", "", "");
this.mapController.animateTo(geoPoint);
this.myItemizedOverlay.setLocation(location);
this.myItemizedOverlay.addOverlay(pcOverlayItem);
this.mapOverlays.add(this.myItemizedOverlay);
// Everytime i get a new location i generate random non player
// characters near my location
int numberOfNonPlayers = new Random().nextInt(5);
for (int i = 0; i < numberOfNonPlayers; i++) {
int radius = (int) this.myMapView.getProjection()
.metersToEquatorPixels(200);
double lowerLimit = -1;
double upperLimit = 1;
Double newLatitude = location.getLatitude()
* 1E6
+ (radius * (lowerLimit + (Math.random() * ((upperLimit - lowerLimit) + 1))));
Double newLongitude = location.getLongitude()
* 1E6
+ (radius * (lowerLimit + (Math.random() * ((upperLimit - lowerLimit) + 1))));
GeoPoint geoPoint2 = new GeoPoint(newLatitude.intValue(),
newLongitude.intValue());
CustomOverlayItem npcOverlayItem = new CustomOverlayItem(
geoPoint2, "", "", "");
Location newLocation = new Location("npc " + i);
newLocation.setLatitude(newLatitude);
newLocation.setLongitude(newLongitude);
this.nonPlayerItemizedOverlay = new NonPlayerItemizedOverlay(
this.nonPlayerDrawable, this.myMapView);
this.nonPlayerItemizedOverlay.setLocation(newLocation);
this.nonPlayerItemizedOverlay.addOverlay(npcOverlayItem);
this.mapOverlays.add(this.nonPlayerItemizedOverlay);
}
}
}
And this is my NonPlayerItemizedOverlay class:
public class NonPlayerItemizedOverlay extends BaseItemizedOverlay {
public NonPlayerItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(defaultMarker, mapView);
// TODO Auto-generated constructor stub
}
private Location location;
public static int metersToRadius(float meters, MapView map, double latitude) {
return (int) (map.getProjection().metersToEquatorPixels(meters) * (1 / Math
.cos(Math.toRadians(latitude))));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
if (shadow == false) {
Projection projection = mapView.getProjection();
// Get the current location
Double latitude = location.getLatitude();
Double longitude = location.getLongitude();
GeoPoint geoPoint = new GeoPoint(latitude.intValue(),
longitude.intValue());
// Convert the location to screen pixels
Point point = new Point();
projection.toPixels(geoPoint, point);
// int radius = metersToRadius(30, mapView, latitude);
int radius = (int) mapView.getProjection()
.metersToEquatorPixels(50);
RectF oval = new RectF(point.x - radius, point.y - radius, point.x
+ radius, point.y + radius);
// Setup the paint
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(2.0f);
paint.setColor(0xffE62020);
paint.setStyle(Style.STROKE);
canvas.drawOval(oval, paint);
paint.setColor(0x18E62020);
paint.setStyle(Style.FILL);
canvas.drawOval(oval, paint);
}
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
And my MyItemizedOverlay class:
public class MyItemizedOverlay extends BaseItemizedOverlay {
public MyItemizedOverlay(Drawable defaultMarker, MapView mapView) {
super(defaultMarker, mapView);
// TODO Auto-generated constructor stub
}
private Location location;
public static int metersToRadius(float meters, MapView map, double latitude) {
return (int) (map.getProjection().metersToEquatorPixels(meters) * (1 / Math
.cos(Math.toRadians(latitude))));
}
#Override
public void draw(Canvas canvas, MapView mapView, boolean shadow) {
super.draw(canvas, mapView, shadow);
if (shadow == false) {
Projection projection = mapView.getProjection();
// Get the current location
Double latitude = location.getLatitude() * 1E6;
Double longitude = location.getLongitude() * 1E6;
GeoPoint geoPoint = new GeoPoint(latitude.intValue(),
longitude.intValue());
// Convert the location to screen pixels
Point point = new Point();
projection.toPixels(geoPoint, point);
// int radius = metersToRadius(100, mapView, latitude);
int radius = (int) mapView.getProjection().metersToEquatorPixels(
200);
RectF oval = new RectF(point.x - radius, point.y - radius, point.x
+ radius, point.y + radius);
// Setup the paint
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setStrokeWidth(2.0f);
paint.setColor(0xff6666ff);
paint.setStyle(Style.STROKE);
canvas.drawOval(oval, paint);
paint.setColor(0x186666ff);
paint.setStyle(Style.FILL);
canvas.drawOval(oval, paint);
}
}
public Location getLocation() {
return location;
}
public void setLocation(Location location) {
this.location = location;
}
The thing is that something weird is happening because all the random locations are too near of my location center, it seems that the formula does not cover the whole radius and i think that distances are not in real meters.
Any idea of what could be wrong with my formula?
Thanks in advance
For questions regarding map projections and coordinate calculations, this SE site could be helpful: http://gis.stackexchange.com (Geographic Information Systems).
To be sure use the distanceTo() formula of location class.You can do it this way:
double distance = a.distanceTo(b);
where a and b are Location objects.

Getting coordinates from json parsing and displaying in mapview?

through jsonparsing i parse all the string values again i need to display the latitude and longitude in the mapview.. where i need to store all the coordinates in a separate array
anyone please help me ..
thanks in advance
I am not sure how is your func of parseString, I assume that you can get 2 string value of lat and long. The remaining part can be done as followed
String coordinates[] = {"...","..."};
double lat = Double.parseDouble(coordinates[0]);
double lng = Double.parseDouble(coordinates[1]);
p = new GeoPoint(
(int) (lat * 1E6),
(int) (lon * 1E6));
//mc is MapView object
mc.animateTo(p);
mc.setZoom(15);
mapView.invalidate();
To display it on the map, you need to create an overlay with a bitmap pinpoint in res/ folder
MarkerOverlay mark = new MarkerOverlay();
listOfOverlays = mapView.getOverlays();
listOfOverlays.clear();
listOfOverlays.add(mark);
mapView.invalidate();
A class of MapOverlay could be defined as such:
class MarkerOverlay extends com.google.android.maps.Overlay
{
//create a constructor here with p.x and p.y as parameters
#Override
public boolean draw(Canvas canvas, MapView mapView,
boolean shadow, long when)
{
super.draw(canvas, mapView, shadow);
Point screenPts = new Point();
Bitmap bmp = BitmapFactory.decodeResource(
getResources(), R.drawable.pushpin);
GeoPoint point = new GeoPoint(
(int) (p.x * 1E6),
(int) (p.y * 1E6));
mapView.getProjection().toPixels(point, screenPts);
canvas.drawBitmap(bmp, screenPts.x-16, screenPts.y-32, null);
canvas.drawText(parts[0],screenPts.x-16 , screenPts.y-40, new Paint());
}
}
}
return true;
}
}

Categories

Resources