地理编码器很棒,感谢 llya。
此查询应在单独的线程中执行,例如 AsyncTask,这是一个示例代码,希望对您有所帮助。
public class AsyncTaskToQueryLocation extends
AsyncTask<String, Integer, LatLng> {
private WeakReference<Context> m_Context;
private WeakReference<UserLocationManager> m_Manager;
private WeakReference<OnGeoLocationQueryListener> m_Listener;
private Locale m_Locale;
private String m_ParsedLocation;
public AsyncTaskToQueryLocation(Context context,
UserLocationManager manager, OnGeoLocationQueryListener listener,
Locale locale) {
m_Context = new WeakReference<Context>(context);
m_Manager = new WeakReference<UserLocationManager>(manager);
m_Listener = new WeakReference<OnGeoLocationQueryListener>(listener);
m_Locale = locale;
m_ParsedLocation = null;
}
@Override
protected LatLng doInBackground(String... params) {
Context context = m_Context.get();
if (context == null) {
return null;
}
if ((params == null) || (params.length == 0) || (params[0] == null)) {
return null;
}
m_ParsedLocation = params[0];
Geocoder geoCoder = new Geocoder(context, m_Locale);
try {
List<Address> addresses = geoCoder.getFromLocationName(
m_ParsedLocation, 1);
if (addresses.size() > 0) {
return new LatLng(addresses.get(0).getLatitude(), addresses
.get(0).getLongitude());
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(LatLng latLng) {
OnGeoLocationQueryListener listener = m_Listener.get();
if (listener != null) {
listener.onGeoLocationQueryFinished(m_ParsedLocation, latLng);
}
onCancelled();
}
@Override
protected void onCancelled() {
UserLocationManager manager = m_Manager.get();
if (manager != null) {
manager.notifyAsyncTaskFinish(AsyncTaskToQueryLocation.class
.getSimpleName());
}
clearReference();
}
private void clearReference() {
// release the weak reference.
m_Listener.clear();
m_Manager.clear();
m_Context.clear();
}
}