如何从android google map v2中的给定地址获取纬度和经度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22909756/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 06:33:18  来源:igfitidea点击:

How to get latitude and longitude from a given address in android google map v2?

androidgoogle-maps

提问by Dheerendra Upadhyay

I am using google map v2 android and map is too displayed in my app. I just want to get latitude and longitude from a given address.

我正在使用谷歌地图 v2 android 并且地图在我的应用程序中显示太多。我只想从给定的地址获取纬度和经度。

Example: In text field if I type "Indore", then I get the latitude and longitude of this city.

示例:在文本字段中,如果我输入“Indore”,那么我会得到这个城市的纬度和经度。

回答by codeRider

You can use this method

你可以使用这个方法

 public void getLatLongFromPlace(String place) {
            try {
                Geocoder selected_place_geocoder = new Geocoder(context);
                List<Address> address;

                address = selected_place_geocoder.getFromLocationName(place, 5);

                if (address == null) {
                    d.dismiss();
                } else {
                    Address location = address.get(0);
                               Latitude lat= location.getLatitude();
                Longitude lng = location.getLongitude();

                }

            } catch (Exception e) {
                e.printStackTrace();
fetchLatLongFromService fetch_latlng_from_service_abc = new fetchLatLongFromService(
                        place.replaceAll("\s+", ""));
                fetch_latlng_from_service_abc.execute();

            }

        }


//Sometimes happens that device gives location = null

    public class fetchLatLongFromService extends
                AsyncTask<Void, Void, StringBuilder> {
            String place;


            public fetchLatLongFromService(String place) {
                super();
                this.place = place;

            }

            @Override
            protected void onCancelled() {
                // TODO Auto-generated method stub
                super.onCancelled();
                this.cancel(true);
            }

            @Override
            protected StringBuilder doInBackground(Void... params) {
                // TODO Auto-generated method stub
                try {
                    HttpURLConnection conn = null;
                    StringBuilder jsonResults = new StringBuilder();
                    String googleMapUrl = "http://maps.googleapis.com/maps/api/geocode/json?address="
                            + this.place + "&sensor=false";

                    URL url = new URL(googleMapUrl);
                    conn = (HttpURLConnection) url.openConnection();
                    InputStreamReader in = new InputStreamReader(
                            conn.getInputStream());
                    int read;
                    char[] buff = new char[1024];
                    while ((read = in.read(buff)) != -1) {
                        jsonResults.append(buff, 0, read);
                    }
                    String a = "";
                    return jsonResults;
                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;

            }

        @Override
        protected void onPostExecute(StringBuilder result) {
            // TODO Auto-generated method stub
            super.onPostExecute(result);
            try {
                JSONObject jsonObj = new JSONObject(result.toString());
                JSONArray resultJsonArray = jsonObj.getJSONArray("results");

                // Extract the Place descriptions from the results
                // resultList = new ArrayList<String>(resultJsonArray.length());

                JSONObject before_geometry_jsonObj = resultJsonArray
                        .getJSONObject(0);

                JSONObject geometry_jsonObj = before_geometry_jsonObj
                        .getJSONObject("geometry");

                JSONObject location_jsonObj = geometry_jsonObj
                        .getJSONObject("location");

                String lat_helper = location_jsonObj.getString("lat");
                double lat = Double.valueOf(lat_helper);


                String lng_helper = location_jsonObj.getString("lng");
                double lng = Double.valueOf(lng_helper);


                LatLng point = new LatLng(lat, lng);


            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();

            }
        }
    }

The usual method to find the location is the one which i had mentioned earlier but sometime the network provider or GPS provider is not able to fetch location thus gives null value,it happened with me also but when the location is null and an exception is thrown,use the google web service to fetch the lat and long.First try to fetch from the above method and if it fails which happens sometimes go with the second method to fetch it from a web service.

查找位置的常用方法是我之前提到的方法,但有时网络提供商或 GPS 提供商无法获取位置,因此给出空值,我也发生过这种情况,但是当位置为空并抛出异常时,使用谷歌网络服务获取经纬度。首先尝试从上述方法中获取,如果失败,有时会使用第二种方法从网络服务中获取它。

回答by Jitesh Upadhyay

hi please use below google api for this purpose!!

嗨,请为此使用下面的 google api !!

http://maps.google.com/maps/api/geocode/json?address=Indore&sensor=false

http://maps.google.com/maps/api/geocode/json?address=Indore&sensor=false

you can use given below function in yours program to fetch latitude and longitude

你可以在你的程序中使用下面给出的函数来获取纬度和经度

public static void getLatLongFromGivenAddress(String youraddress) {
    String uri = "http://maps.google.com/maps/api/geocode/json?address=" +
                  youraddress + "&sensor=false"
    HttpGet httpGet = new HttpGet(uri);
    HttpClient client = new DefaultHttpClient();
    HttpResponse response;
    StringBuilder stringBuilder = new StringBuilder();

    try {
        response = client.execute(httpGet);
        HttpEntity entity = response.getEntity();
        InputStream stream = entity.getContent();
        int b;
        while ((b = stream.read()) != -1) {
            stringBuilder.append((char) b);
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }

    JSONObject jsonObject = new JSONObject();
    try {
        jsonObject = new JSONObject(stringBuilder.toString());

        lng = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lng");

        lat = ((JSONArray)jsonObject.get("results")).getJSONObject(0)
            .getJSONObject("geometry").getJSONObject("location")
            .getDouble("lat");

        Log.d("latitude", lat);
        Log.d("longitude", lng);
    } catch (JSONException e) {
        e.printStackTrace();
    }

}

to check this api please visit below link

要检查这个 api 请访问下面的链接

http://maps.google.com/maps/api/geocode/json?address=Indore&sensor=false

http://maps.google.com/maps/api/geocode/json?address=Indore&sensor=false

you will get following json which you need to parse

您将获得以下需要解析的 json

{
   "results" : [
      {
         "address_components" : [
            {
               "long_name" : "Indore",
               "short_name" : "Indore",
               "types" : [ "locality", "political" ]
            },
            {
               "long_name" : "Indore",
               "short_name" : "Indore",
               "types" : [ "administrative_area_level_2", "political" ]
            },
            {
               "long_name" : "Madhya Pradesh",
               "short_name" : "MP",
               "types" : [ "administrative_area_level_1", "political" ]
            },
            {
               "long_name" : "India",
               "short_name" : "IN",
               "types" : [ "country", "political" ]
            }
         ],
         "formatted_address" : "Indore, Madhya Pradesh, India",
         "geometry" : {
            "bounds" : {
               "northeast" : {
                  "lat" : 22.8485735,
                  "lng" : 75.965395
               },
               "southwest" : {
                  "lat" : 22.6076326,
                  "lng" : 75.7411195
               }
            },
            "location" : {
               "lat" : 22.7195687,
               "lng" : 75.8577258
            },
            "location_type" : "APPROXIMATE",
            "viewport" : {
               "northeast" : {
                  "lat" : 22.8485735,
                  "lng" : 75.965395
               },
               "southwest" : {
                  "lat" : 22.6076326,
                  "lng" : 75.7411195
               }
            }
         },
         "types" : [ "locality", "political" ]
      }
   ],
   "status" : "OK"
}

you can do also as follows

你也可以做如下

public  void getLatLongFromGivenAddress(String address)
        {
              double lat= 0.0, lng= 0.0;

            Geocoder geoCoder = new Geocoder(this, Locale.getDefault());    
            try 
            {
                List<Address> addresses = geoCoder.getFromLocationName(address , 1);
                if (addresses.size() > 0) 
                {            
                    GeoPoint p = new GeoPoint(
                            (int) (addresses.get(0).getLatitude() * 1E6), 
                            (int) (addresses.get(0).getLongitude() * 1E6));

                    lat=p.getLatitudeE6()/1E6;
                    lng=p.getLongitudeE6()/1E6;

                    Log.d("Latitude", ""+lat);
                Log.d("Longitude", ""+lng);
                }
            }
            catch(Exception e)
            {
              e.printStackTrace();
            }
        }
    }

回答by cYrixmorten

So far all the answers seems valid, using either the geocode API or the Geocoder object, just wanted to point you towards this: Google Geocoder service is unavaliable (Coordinates to address)

到目前为止,所有答案似乎都有效,使用地理编码 API 或地理编码器对象,只是想向您指出这一点:Google Geocoder 服务不可用(要寻址的坐标)

I do not know how frequent this problem occurs but from time to time some devices cannot use the Geocoder object, so what I did was combining both methods, falling back to the HTTP geocode API.

我不知道这个问题发生的频率有多高,但有时有些设备无法使用 Geocoder 对象,所以我所做的是将这两种方法结合起来,退回到 HTTP 地理编码 API。

Happy coding

快乐编码

回答by jitain sharma

Just use the following code and you will get what you want:

只需使用以下代码,你就会得到你想要的:

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(ctx, Locale.getDefault());
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);

Where 1 is the limit to get the maxResults.

其中 1 是获得 maxResults 的限制。