16

我想在我的应用程序中使用 map api 2 进行反向地理编码。但我不知道该怎么做?有什么想法吗?

4

5 回答 5

17

使用地理编码器

Geocoder geoCoder = new Geocoder(context);
List<Address> matches = geoCoder.getFromLocation(latitude, longitude, 1);
Address bestMatch = (matches.isEmpty() ? null : matches.get(0));
于 2013-03-03T21:25:09.553 回答
9

您可以通过两种方式进行反向地理编码

  • 地理编码器
  • 谷歌 API

Geocoder 应该在单独的线程中执行:

private class FindPlaces extends AsyncTask<String, Void, List<Address>> {

    @Override
    protected List<Address> doInBackground(String... params) {
        if (act == null)
            this.cancel(true);
        Geocoder geocoder = new Geocoder(act, Locale.getDefault());
        try {
            addresses = geocoder.getFromLocation(
                    Double.parseDouble(params[0]),
                    Double.parseDouble(params[1]), result);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return addresses;
    }

    @Override
    protected void onPostExecute(List<Address> addresses) {
        super.onPostExecute(addresses);
        if (act == null)
            return;
        if (addresses == null || addresses.size() == 0) {
            Toast.makeText(act, "No location found", Toast.LENGTH_SHORT)
                    .show();
            return;
        }
        address = addresses.get(0);

        String aLine = "";
        for (int addr = 0; addr <= address.getMaxAddressLineIndex() - 2; addr++) {
            aLine = aLine.length() > 0 ? aLine + ", "
                    + String.valueOf(address.getAddressLine(addr)) : String
                    .valueOf(address.getAddressLine(addr));
        }
        address.setAddressLine(0, aLine);
        if (act == null)
            return;

    }
}

Google API 1) 在 google 控制台中启用 Google Maps Geocoding API 2) 在此 url https://maps.googleapis.com/maps/api/geocode/json?latlng=中连接您的 latlong

例如: https ://maps.googleapis.com/maps/api/geocode/json?latlng=youlatitude,yourlongitude&key=yourapikey

用你的 latlog 调用下面的 asyntask 这对我有用..

public class ReverseGecoding extends AsyncTask<Double, Void, String> {

Context context;**
private Address address;
private String GEOCODINGKEY = "&key=YourKey";
private String REVERSE_GEOCODING_URL = "https://maps.googleapis.com/maps/api/geocode/json?latlng=";

public ReverseGecoding(Context context) {
    this.context = context;
    this.listener = listener;
}

@Override
protected String doInBackground(Double... params) {
    if (params[0] != null) {
         String result = "";
    try {
        String mUrl = REVERSE_GEOCODING_URL + params[0] + ","
                + params[1] + GEOCODINGKEY;

        URL url = new URL(mUrl);
        HttpURLConnection httpsURLConnection = (HttpURLConnection) url.openConnection();
        httpsURLConnection.setReadTimeout(10000);
        httpsURLConnection.setConnectTimeout(15000);
        httpsURLConnection.setDoInput(true);
        httpsURLConnection.setRequestMethod("GET");
        httpsURLConnection.connect();
        int mStatus = httpsURLConnection.getResponseCode();
        if (mStatus == 200)
            return readResponse(httpsURLConnection.getInputStream()).toString();
        return result;

    } catch (Exception e) {
        e.printStackTrace();

    }
    return null;

}



private static StringBuilder readResponse(InputStream inputStream) throws IOException, NullPointerException {
        BufferedReader r = new BufferedReader(new InputStreamReader(inputStream));
        StringBuilder stringBuilder = new StringBuilder();
        String line;
        while ((line = r.readLine()) != null) {
            stringBuilder.append(line);
        }
        return stringBuilder;
    }
}
于 2015-10-16T07:43:01.007 回答
3

这就是它对我有用的方式..

MarkerOptions markerOptions;

 Location myLocation;
 Button btLocInfo;

String selectedLocAddress;
     private GoogleMap myMap;
LatLng latLng;
 LatLng tmpLatLng;
    @Override
public void onMapLongClick(LatLng point) {

    // Getting the Latitude and Longitude of the touched location
    latLng = point;
    // Clears the previously touched position
    myMap.clear();
    // Animating to the touched position
    myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    // Creating a marker
    markerOptions = new MarkerOptions();
    // Setting the position for the marker
    markerOptions.position(latLng);
    // Adding Marker on the touched location with address

    new ReverseGeocodingTask(getBaseContext()).execute(latLng);
    //tmpLatLng = latLng;

    btLocInfo.setEnabled(true);


    btLocInfo.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            double[] coordinates={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};

            double latitude = tmpLatLng.latitude;
            double longitude = tmpLatLng.longitude;

            Log.i("selectedCoordinates", latitude + " " + longitude);
            Log.i("selectedLocAddress", selectedLocAddress);


        }
    });
}


private class ReverseGeocodingTask extends AsyncTask<LatLng, Void, String>{
    Context mContext;
    public ReverseGeocodingTask(Context context){
        super();
        mContext = context;
        }
    // Finding address using reverse geocoding
    @Override
    protected String doInBackground(LatLng... params) {
        Geocoder geocoder = new Geocoder(mContext);
        double latitude = params[0].latitude;
        double longitude = params[0].longitude;
        List<Address> addresses = null;
        String addressText="";
        try {
            addresses = geocoder.getFromLocation(latitude, longitude,1);
            Thread.sleep(500);


        if(addresses != null && addresses.size() > 0 ){
            Address address = addresses.get(0);
            addressText = String.format("%s, %s, %s",
                    address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                            address.getLocality(),
                            address.getCountryName());
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        selectedLocAddress = addressText;
        return addressText;
    }

    @Override
    protected void onPostExecute(String addressText) {
        // Setting the title for the marker.
        // This will be displayed on taping the marker
        markerOptions.title(addressText);
        // Placing a marker on the touched position
        myMap.addMarker(markerOptions);
        }
    }
于 2013-04-17T08:58:33.080 回答
2

您可以这样做以获得完整的地址:

public class MainActivity extends AppCompatActivity {

     ...

private Geocoder geocoder;
private TextView mAddressTxtVu;

     ...


// assume that you got latitude and longitude correctly 

mLatitude  =  20.23232
mLongitude =  32.999

String errorMessage = "";

geocoder = new Geocoder(context, Locale.getDefault());

List<Address> addresses = null;

try {
          addresses = geocoder.getFromLocation(
                   mlattitude,
                   mlongitude,
                   1);
  } catch (IOException e) {
          errorMessage = getString(R.string.service_not_available);
          Log.e(TAG, errorMessage, e);
  } catch (IllegalArgumentException illegalArgumentException) {
                    // Catch invalid latitude or longitude values.
          errorMessage = getString(R.string.invalid_lat_long_used);
          Log.e(TAG, errorMessage + ". " + "Latitude = " + mlattitude +", 
  Longitude = " + mlongitude, illegalArgumentException);
  }

  // Handle case where no address was found.
  if (addresses == null || addresses.size() == 0) {
         if (errorMessage.isEmpty()) {
                  errorMessage = getString(R.string.no_address_found);
                  Log.e(TAG, errorMessage);
         }

  } else {
         Address address = addresses.get(0);
         ArrayList<String> addressFragments = new ArrayList<String>();

         // Fetch the address lines using getAddressLine,
         // join them, and send them to the thread.
         for (int i = 0; i <= address.getMaxAddressLineIndex(); i++) {
                  addressFragments.add(address.getAddressLine(i));
         }
         // Log.i(TAG, getString(R.string.address_found));


  mAddressTxtVu.setText(TextUtils.join(System.getProperty("line.separator"),
                            addressFragments));
                }

希望能帮助到你!

于 2019-06-17T11:20:51.150 回答
0

您无需为此目的使用 Google Maps Api。Android SKD 有一个类,您可以简单地使用它而无需注册任何 API 密钥等。班级是android.location.Geocoder。它具有地理编码和反向地理编码的方法。我在查看这个类的源代码,发现它有一个方法android.location.Geocoder#getFromLocationName(java.lang.String, int),第一个参数是地址,第二个是你想要的最大结果数。它返回一个List<Address>. 该类具有和之Address类的方法。他们都回来了。android.location.Address#getLatitudeandroid.location.Address#getLongitudedouble

试试看,让我知道它有多好:-)

于 2018-08-10T13:21:08.577 回答