2013-09-27 33 views
8

我正在开发一个接收给定地址的Android应用程序。我只想让应用程序在设备上运行,如果用户位于该地址或更靠近该地址。如何知道Android设备是否在地址附近google maps api

是否有可能只做谷歌地图API?

+0

当用户试图启动应用程序,是不是你的理想的范围内,会发生什么? – Prmths

+0

也许这可以帮助你:http://stackoverflow.com/questions/3652951/google-maps-api-get-coordinates-of-address。你基本上需要比较两组坐标,并找出这两对是否足够接近。 – Izmaki

+0

@Prmths应用程序将无法打开:) –

回答

6

你可以得到ADRESS从ADRESS获得的纬度和经度:

Geocoder coder = new Geocoder(this); 
List<Address> address; 

try { 
    address = coder.getFromLocationName(strAddress,5); 
    if (address == null) { 
     return null; 
    } 
    Address location = address.get(0); 
    location.getLatitude(); 
    location.getLongitude(); 


} 

然后将它与您的位置比较

if (distance(mylocation.latitude, mylocation.longitude, location.getLatitude(), location.getLongitude()) < 0.1) { // if distance < 0.1 

    // launch the activity 
}else { 
    finish(); 
} 


/** calculates the distance between two locations in MILES */ 
private double distance(double lat1, double lng1, double lat2, double lng2) { 

    double earthRadius = 3958.75; // in miles, change to 6371 for kilometers 

    double dLat = Math.toRadians(lat2-lat1); 
    double dLng = Math.toRadians(lng2-lng1); 

    double sindLat = Math.sin(dLat/2); 
    double sindLng = Math.sin(dLng/2); 

    double a = Math.pow(sindLat, 2) + Math.pow(sindLng, 2) 
     * Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)); 

    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); 

    double dist = earthRadius * c; 

    return dist; 
} 

编辑: 作为@FelipeMosso说的话您还可以使用distanceBetween来计算两个位置之间的近似距离(米)或distanceTo,该距离为您提供了所处位置与目的地..

+0

谢谢@Dyna!当我回到家时,我会看看这个,我反馈给您回复 –

+0

您的想法对我有用!但之前我已经搜索了一点,我发现了一个名为distanceBetween的Location类的Android方法,它可以完成与距离方法相同的操作。如果有人遇到同样的问题,我建议您使用:http://developer.android.com/reference/android/location/Location.html –

+0

确定@FelipeMosso。我会通过链接更新我的答案,以便我们可以帮助其他开发人员解决此问题。干杯* – Dyna

2

GMSCore位置API还具有地理编码,它允许您检测设备与一个或多个地理栅栏位置的接近程度。您可以使用地图获取地址的经纬度。

这不会阻止您的应用程序运行。更好的解决方案是启动应用程序,然后让它进入后台。当用户穿过Geofence时,发出通知。当用户点击通知时,调出一个活动。

Creating and Monitoring Geofences

相关问题