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

如何在android google map v2中从给定地址获取纬度和经度?,android,google-maps,Android,Google Maps,我使用的是谷歌地图v2安卓系统,地图也显示在我的应用程序中。 我只想从给定的地址得到纬度和经度 示例:在文本字段中,如果我键入“Indore”,那么我将获得该城市的纬度和经度。只需使用以下代码,您将获得所需的: Geocoder geocoder; List<Address> addresses; geocoder = new Geocoder(ctx, Locale.getDefault()); addresses = geocoder.getFromLocation(locati

我使用的是谷歌地图v2安卓系统,地图也显示在我的应用程序中。 我只想从给定的地址得到纬度和经度


示例:在文本字段中,如果我键入“Indore”,那么我将获得该城市的纬度和经度。

只需使用以下代码,您将获得所需的:

Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(ctx, Locale.getDefault());
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
Geocoder-Geocoder;
列出地址;
geocoder=新的geocoder(ctx,Locale.getDefault());
addresses=geocoder.getFromLocation(location.getLatitude(),location.getLatitude(),1);

其中1是获取最大结果的限制。

您可以使用此方法

 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();

            }
        }
    }
public void getLatLongFromPlace(字符串位置){
试一试{
所选地理编码器\u地点\u地理编码器=新地理编码器(上下文);
名单地址;
地址=所选地点地理编码器。getFromLocationName(地点,5);
如果(地址==null){
d、 解雇();
}否则{
地址位置=地址。获取(0);
纬度纬度=位置。getLatitude();
经度lng=location.getLongitude();
}
}捕获(例外e){
e、 printStackTrace();
fetchLatLongFromService fetch\u latlng\u from\u service\u abc=新fetchLatLongFromService(
place.replaceAll(“\\s+”,“);
从_服务_abc.execute()获取_latlng_;
}
}
//有时,设备会给出location=null
公共类fetchLatLongFromService扩展
异步任务{
串位;
公共fetchLatLongFromService(字符串位置){
超级();
这个地方=地方;
}
@凌驾
受保护的void onCancelled(){
//TODO自动生成的方法存根
super.onCancelled();
这个。取消(true);
}
@凌驾
受保护的StringBuilder doInBackground(无效…参数){
//TODO自动生成的方法存根
试一试{
HttpURLConnection conn=null;
StringBuilder jsonResults=新建StringBuilder();
字符串googleMapUrl=”http://maps.googleapis.com/maps/api/geocode/json?address="
+this.place+“&sensor=false”;
URL=新URL(谷歌地图URL);
conn=(HttpURLConnection)url.openConnection();
InputStreamReader in=新的InputStreamReader(
conn.getInputStream());
int-read;
char[]buff=新字符[1024];
while((read=in.read(buff))!=-1){
附加(buff,0,read);
}
字符串a=“”;
返回结果;
}捕获(例外e){
e、 printStackTrace();
}
返回null;
}
@凌驾
PostExecute上受保护的void(StringBuilder结果){
//TODO自动生成的方法存根
super.onPostExecute(结果);
试一试{
JSONObject jsonObj=新的JSONObject(result.toString());
JSONArray resultJsonArray=jsonObj.getJSONArray(“结果”);
//从结果中提取位置描述
//resultList=newarraylist(resultJsonArray.length());
几何体之前的JSONObject\u JSONObject=resultJsonArray
.getJSONObject(0);
JSONObject geometry\u jsonObj=在\u geometry\u jsonObj之前
.getJSONObject(“几何体”);
JSONObject位置=几何体
.getJSONObject(“位置”);
String lat_helper=location_jsonObj.getString(“lat”);
double lat=double.valueOf(lat_helper);
String lng_helper=location_jsonObj.getString(“lng”);
双液化天然气=双液化天然气的价值;
LatLng点=新LatLng(lat,lng);
}捕获(JSONException e){
//TODO自动生成的捕捉块
e、 printStackTrace();
}
}
}

查找位置的常用方法是我前面提到的方法,但有时网络提供商或GPS提供商无法获取位置,因此给出空值,我也会遇到这种情况,但当位置为空并引发异常时,使用google web服务获取lat和long。首先尝试从上面的方法获取,如果失败,有时会使用第二种方法从web服务获取。

嗨,请使用下面的google api

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

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();
    }

}
要检查此api,请访问以下链接

您将得到需要解析的以下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"
}
您还可以执行以下操作

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();
            }
        }
    }
public void getLatlongfrom给定地址(字符串地址)
{
双lat=0.0,lng=0.0;
Geocoder Geocoder=新的Geocoder(这个,Locale.getDefault());
尝试
{
列表地址=geoCoder.getFromLocationName(地址,1);
如果(地址.size()>0)
{            
地质点p=新的地质点(
(int)(addresses.get(0.getLatitude()*1E6),
(int)(addresses.get(0.getLongitude()*1E6));
lat=p.getlatudee6()/1E6;
lng=p.getLongitudeE6()/1E6;
对数d(“纬度”,“纬度+纬度”);
对数d(“经度”,“液化天然气”);
}
}