[英]Get location (latitude / longitude) from address without city in Android
我試圖找到沒有城市的街道地址(緯度/經度) - 例如“123 Main St.” - 最接近當前位置。 此功能內置於Google Maps應用程序以及iOS地圖api中,因此令人驚訝地發現它缺少Android - 例如調用Geocoder.getFromLocation()並讓平台插入參考點。 我嘗試了幾種解決方案,以下是最好的,但仍然感覺自卑。
我使用左下角和右上角坐標調用Geocoder.getFromLocationName()。 呼叫從當前位置周圍的10kmx10km區域開始,並重復(30x30,100x100,然后沒有邊界框參數),直到返回一些地址。 返回多個地址時,計算並使用最接近的地址:
更新:這種方法似乎對於在邊界之外容易找到的地址效率低下。 例如,從紐約西海岸搜索“紐約,紐約”或“波士頓” - 需要3個有界和1個無限制的Geocoder.getFromLocation()調用。 然而,毫無疑問,在第一次調用時,紐約和波士頓會返回正確的lat / lng,CA中有最嚴格的界限。 谷歌很聰明,無視我們的界限。 這可能會給某些人帶來問題,但這種方法很有用。
package com.puurbuy.android;
import java.io.IOException;
import java.util.List;
import android.content.Context;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.os.AsyncTask;
import android.util.Log;
public class GeocoderRunner extends AsyncTask<String, Void, Address> {
final static double LON_DEG_PER_KM = 0.012682308180089;
final static double LAT_DEG_PER_KM =0.009009009009009;
final static double[] SEARCH_RANGES = {10, 50,800,-1}; //city, region, state, everywhere
private Context mContext;
private GeocoderListener mListener;
private Location mLocation;
public GeocoderRunner(Context context, Location location,
GeocoderListener addressLookupListener) {
mContext = context;
mLocation = location;
mListener = addressLookupListener;
}
@Override
protected Address doInBackground(String... params) {
Geocoder geocoder = new Geocoder(mContext);
List<Address> addresses = null;
//reference location TODO handle null
double lat = mLocation.getLatitude();
double lon = mLocation.getLongitude();
int i = 0;
try {
//loop through SEARCH_RANGES until addresses are returned
do{
//if range is -1, call getFromLocationName() without bounding box
if(SEARCH_RANGES[i] != -1){
//calculate bounding box
double lowerLeftLatitude = translateLat(lat,-SEARCH_RANGES[i]);
double lowerLeftLongitude = translateLon(lon,SEARCH_RANGES[i]);
double upperRightLatitude = translateLat(lat,SEARCH_RANGES[i]);
double upperRightLongitude = translateLon(lon,-SEARCH_RANGES[i]);
addresses = geocoder.getFromLocationName(params[0], 5, lowerLeftLatitude, lowerLeftLongitude, upperRightLatitude, upperRightLongitude);
} else {
//last resort, try unbounded call with 20 result
addresses = geocoder.getFromLocationName(params[0], 20);
}
i++;
}while((addresses == null || addresses.size() == 0) && i < SEARCH_RANGES.length );
} catch (IOException e) {
Log.i(this.getClass().getSimpleName(),"Gecoder lookup failed! " +e.getMessage());
}
if(addresses == null ||addresses.size() == 0)
return null;
//If multiple addresses were returned, find the closest
if(addresses.size() > 1){
Address closest = null;
for(Address address: addresses){
if(closest == null)
closest = address;
else
closest = getClosest(mLocation, closest,address);//returns the address that is closest to mLocation
}
return closest;
}else
return addresses.get(0);
}
@Override
protected void onPostExecute(Address address) {
if(address == null)
mListener.lookupFailed();
else
mListener.addressReceived(address);
}
//Listener callback
public interface GeocoderListener{
public void addressReceived(Address address);
public void lookupFailed();
}
//HELPER Methods
private static double translateLat(double lat, double dx){
if(lat > 0 )
return (lat + dx*LAT_DEG_PER_KM);
else
return (lat - dx*LAT_DEG_PER_KM);
}
private static double translateLon(double lon, double dy){
if(lon > 0 )
return (lon + dy*LON_DEG_PER_KM);
else
return (lon - dy*LON_DEG_PER_KM);
}
private static Address getClosest(Location ref, Address address1, Address address2){
double xO = ref.getLatitude();
double yO = ref.getLongitude();
double x1 = address1.getLatitude();
double y1 = address1.getLongitude();
double x2 = address2.getLatitude();
double y2 = address2.getLongitude();
double d1 = distance(xO,yO,x1,y1);
double d2 = distance(xO,yO,x2,y2);
if(d1 < d2)
return address1;
else
return address2;
}
private static double distance(double x1, double y1, double x2, double y2){
return Math.sqrt((x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
}
}
也許這是最好的解決方案,但我想知道是否有辦法在一次通話中完成此操作。
您的代碼看起來太復雜了,這里有更簡單的方法:
String searchPattern = "123 Main St."
LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//I use last known location, but here we can get real location
Location lastKnownLocation = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
List<Address> addresses = null;
try {
//trying to get all possible addresses by search pattern
addresses = (new Geocoder(this)).getFromLocationName(searchPattern, Integer.MAX_VALUE);
} catch (IOException e) {
}
if (addresses == null || lastKnownLocation == null) {
// location service unavailable or incorrect address
// so returns null
return null;
}
Address closest = null;
float closestDistance = Float.MAX_VALUE;
// look for address, closest to our location
for (Address adr : addresses) {
if (closest == null) {
closest = adr;
} else {
float[] result = new float[1];
Location.distanceBetween(lastKnownLocation.getLatitude(), lastKnownLocation.getLongitude(), adr.getLatitude(), adr.getLongitude(), result);
float distance = result[0];
if (distance < closestDistance) {
closest = adr;
closestDistance = distance;
}
}
}
return closest; //here can be null if we did not find any addresses by search pattern.
我嘗試了Jin35的建議並增加了Geocoder.getFromLocationName()的max_results,但結果並不理想。 首先,大的max_result,無限制的調用比我的模擬器上的5個結果,geocoord有界調用花了更長的時間(2.5x - 7x = 1 - 6秒)。 也許現實世界會更快,這個因素變得不那么重要了。
殺手是無論max_results是50還是100, 每次只有20個結果回來 。 似乎Google正在限制服務器端的結果。 最接近的“123 Main St”對我來說並不是那20個結果 - 從加利福尼亞州的Mt View進行測試,然后返回加利福尼亞州的Oakley。
除非Geocoder.getFromLocationName()之外的其他方法用於進行地址查找,或者更好的方式來使用邊界坐標,我將接受我自己的原始答案。
getFromLocationName(String locationName, int maxResults, double lowerLeftLatitude, double lowerLeftLongitude, double upperRightLatitude, double upperRightLongitude)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.