Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/188.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在google maps api 2 android中反转地理代码_Android_Google Maps Android Api 2 - Fatal编程技术网

如何在google maps api 2 android中反转地理代码

如何在google maps api 2 android中反转地理代码,android,google-maps-android-api-2,Android,Google Maps Android Api 2,我想在我的应用程序中使用MAPAPI2进行反向地理编码。但我不知道该怎么做?有什么想法吗 使用: Geocoder-Geocoder=新的地理编码器(上下文); 列表匹配=geoCoder.getFromLocation(纬度、经度,1); 地址bestMatch=(matches.isEmpty()?null:matches.get(0)); 这就是我的工作方式 MarkerOptions markerOptions; Location myLocation; Button btLocI

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

使用:

Geocoder-Geocoder=新的地理编码器(上下文);
列表匹配=geoCoder.getFromLocation(纬度、经度,1);
地址bestMatch=(matches.isEmpty()?null:matches.get(0));

这就是我的工作方式

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);
        }
    }
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;
    }
}
标记选项标记选项;
位置;
按钮btLocInfo;
字符串selectedLocAddress;
私人谷歌地图;
LatLng LatLng;
LatLng tmpLatLng;
@凌驾
在马普隆喀喇克(LatLng点)上的公共空隙{
//获取被触摸位置的纬度和经度
latLng=点;
//清除先前触摸的位置
myMap.clear();
//设置动画到被触摸的位置
myMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
//创建标记
markerOptions=新的markerOptions();
//设置标记器的位置
标记选项位置(板条);
//在带有地址的触摸位置上添加标记
新建ReverseGeocodingTask(getBaseContext()).execute(latLng);
//tmpLatLng=latLng;
btLocInfo.setEnabled(真);
btLocInfo.setOnClickListener(新的OnClickListener(){
@凌驾
公共void onClick(视图v){
//TODO自动生成的方法存根
双[]坐标={tmpLatLng.latitude/1E6,tmpLatLng.longitude/1E6};
双纬度=tmpLatLng.纬度;
双经度=tmpLatLng.longitude;
Log.i(“选定坐标”,纬度+“”+经度);
Log.i(“selectedLocAddress”,selectedLocAddress);
}
});
}
私有类ReverseGeocodingTask扩展了AsyncTask{
语境;
公共反向分类任务(上下文){
超级();
mContext=上下文;
}
//使用反向地理编码查找地址
@凌驾
受保护管柱后台(LatLng…参数){
Geocoder Geocoder=新的Geocoder(mContext);
双纬度=参数[0]。纬度;
双经度=参数[0]。经度;
列表地址=空;
字符串addressText=“”;
试一试{
地址=地理编码器.getFromLocation(纬度,经度,1);
睡眠(500);
if(addresses!=null&&addresses.size()>0){
地址=地址。获取(0);
addressText=String.format(“%s,%s,%s”,
address.getMaxAddressLineIndex()>0?address.getAddressLine(0):“”,
address.getLocation(),
address.getCountryName());
}
}
捕获(IOE异常){
e、 printStackTrace();
}捕捉(中断异常e){
e、 printStackTrace();
}
selectedLocAddress=地址文本;
返回地址文本;
}
@凌驾
受保护的void onPostExecute(字符串地址文本){
//设置标记的标题。
//这将在录制标记时显示
标记选项。标题(地址文本);
//在触摸的位置放置标记
myMap.addMarker(markerOptions);
}
}

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

  • 地理编码器
  • 谷歌API
地理编码器 它应该在单独的线程中执行:

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;

    }
}

私有类FindPlaces扩展了AsyncTask您不需要为此使用Google Maps Api。Android SKD有一个类,您可以简单地使用它,而无需注册API密钥等等。该类是
android.location.Geocoder
。它有地理编码和反向地理编码的方法。我查看了这个类的源代码,发现它有一个方法
android.location.Geocoder#getFromLocationName(java.lang.String,int)
,其中第一个参数是地址,第二个是所需的最大结果数。它返回一个
列表
Address
类有类似于
android.location.Address#getLatitude
android.location.Address#getLongitude
的方法。它们都返回
double


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

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

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));
                }
public类MainActivity扩展了AppCompatActivity{
...
私人地理编码器;
私人TextView mAddressTxtVu;
...
//假设你得到了正确的纬度和经度
mLatitude=20.23232
长度=32.999
字符串errorMessage=“”;
geocoder=新的geocoder(context,Locale.getDefault());
列表地址=空;
试一试{
地址=geocoder.getFromLocation(
态度,,
长,
1);
}捕获(IOE异常){
errorMessage=getString(R.string.service\u不可用);
Log.e(标签、错误消息、e);
}捕获(IllegalArgumentException IllegalArgumentException){
//捕获无效的纬度或经度值。
errorMessage=getString(使用了R.string.invalid\u lat\u long\u);
Log.e(标签,errorMessage+“+”纬度=“+MLAITATITY+”,
经度=“+m长度,非法辩论除外);
}
//处理找不到地址的情况。
if(addresses==null | | addresses.size()==0){
if(errorMessage.isEmpty()){
errorMessage=getString(R.string.未找到地址);
Log.e(标签、错误消息);
}
}否则{
地址=地址。获取(0);
ArrayList addressFragments=新的ArrayList();
//使用getAddressLine获取地址行,
//加入它们,并将它们发送到线程。

对于(int i=0;我已经为地理编码做了这项工作,它很有效。我的问题是我想做反向地理编码。从地图的角度获取地址。但是无论如何,谢谢!地理编码也做反向地理编码-我已经将代码更新为
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));
                }