Android 如何从地址中找到纬度和经度?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3574644/
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 10:49:15  来源:igfitidea点击:

How can I find the latitude and longitude from address?

androidgoogle-mapsgoogle-geocoder

提问by Kandha

I want to show the location of an address in Google Maps.

我想在 Google 地图中显示地址的位置。

How do I get the latitude and longitude of an address using the Google Maps API?

如何使用 Google Maps API 获取地址的纬度和经度?

回答by ud_an

public GeoPoint getLocationFromAddress(String strAddress){

Geocoder coder = new Geocoder(this);
List<Address> address;
GeoPoint p1 = null;

try {
    address = coder.getFromLocationName(strAddress,5);
    if (address==null) {
       return null;
    }
    Address location=address.get(0);
    location.getLatitude();
    location.getLongitude();

    p1 = new GeoPoint((double) (location.getLatitude() * 1E6),
                      (double) (location.getLongitude() * 1E6));

    return p1;
    }
}

strAddressis a string containing the address. The addressvariable holds the converted addresses.

strAddress是一个包含地址的字符串。该address变量保存转换后的地址。

回答by Nayanesh Gupte

Ud_an's solution with updated API's

带有更新 API 的 Ud_an 解决方案

Note: LatLngclass is part of Google Play Services.

注意LatLng类是 Google Play 服务的一部分。

Mandatory:

强制性

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<uses-permission android:name="android.permission.INTERNET"/>

Update:If you have target SDK 23 and above, make sure you take care of runtime permission for location.

更新:如果您有目标 SDK 23 及更高版本,请确保您注意位置的运行时权限。

public LatLng getLocationFromAddress(Context context,String strAddress) {

    Geocoder coder = new Geocoder(context);
    List<Address> address;
    LatLng p1 = null;

    try {
        // May throw an IOException
        address = coder.getFromLocationName(strAddress, 5);
        if (address == null) {
            return null;
        }

        Address location = address.get(0);
        p1 = new LatLng(location.getLatitude(), location.getLongitude() );

    } catch (IOException ex) {

        ex.printStackTrace();
    }

    return p1;
}

回答by Nirav Dangi

If you want to place your address in google map then easy way to use following

如果您想将您的地址放在谷歌地图中,​​那么使用以下简单方法

Intent searchAddress = new  Intent(Intent.ACTION_VIEW,Uri.parse("geo:0,0?q="+address));
startActivity(searchAddress);

OR

或者

if you needed to get lat long from your address then use Google Place Apifollowing

如果您需要从您的地址获得经纬度,请使用以下Google Place Api

create a method that returns a JSONObjectwith the response of the HTTP Calllike following

创建一个方法,该方法返回一个JSONObjectHTTP 调用的响应,如下所示

public static JSONObject getLocationInfo(String address) {
        StringBuilder stringBuilder = new StringBuilder();
        try {

        address = address.replaceAll(" ","%20");    

        HttpPost httppost = new HttpPost("http://maps.google.com/maps/api/geocode/json?address=" + address + "&sensor=false");
        HttpClient client = new DefaultHttpClient();
        HttpResponse response;
        stringBuilder = new StringBuilder();


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

        JSONObject jsonObject = new JSONObject();
        try {
            jsonObject = new JSONObject(stringBuilder.toString());
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return jsonObject;
    }

now pass that JSONObjectto getLatLong() method like following

现在将该JSONObject传递给 getLatLong() 方法,如下所示

public static boolean getLatLong(JSONObject jsonObject) {

        try {

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

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

        } catch (JSONException e) {
            return false;

        }

        return true;
    }

I hope this helps to you nd others..!! Thank you..!!

我希望这对你和其他人有帮助..!! 谢谢..!!

回答by Neutrino

The following code will work for google apiv2:

以下代码适用于 google apiv2:

public void convertAddress() {
    if (address != null && !address.isEmpty()) {
        try {
            List<Address> addressList = geoCoder.getFromLocationName(address, 1);
            if (addressList != null && addressList.size() > 0) {
                double lat = addressList.get(0).getLatitude();
                double lng = addressList.get(0).getLongitude();
            }
        } catch (Exception e) {
            e.printStackTrace();
        } // end catch
    } // end if
} // end convertAddress

Where address is the String (123 Testing Rd City State zip) you want to convert to LatLng.

其中 address 是您要转换为 LatLng 的字符串(123 Testing Rd City State zip)。

回答by Rakesh Gondaliya

This is how you can find the latitude and longitude of where we have click on map.

这就是您可以找到我们在地图上单击的位置的纬度和经度的方法。

public boolean onTouchEvent(MotionEvent event, MapView mapView) 
{   
    //---when user lifts his finger---
    if (event.getAction() == 1) 
    {                
        GeoPoint p = mapView.getProjection().fromPixels(
            (int) event.getX(),
            (int) event.getY());

        Toast.makeText(getBaseContext(), 
             p.getLatitudeE6() / 1E6 + "," + 
             p.getLongitudeE6() /1E6 , 
             Toast.LENGTH_SHORT).show();
    }                            
    return false;
} 

it works well.

它运作良好。

To get the location's address we can use geocoder class.

要获取位置的地址,我们可以使用地理编码器类。

回答by ylag75

An answer to Kandha problem above :

上面 Kandha 问题的答案:

It throws the "java.io.IOException service not available" i already gave those permission and include the library...i can get map view...it throws that IOException at geocoder...

它抛出“java.io.IOException 服务不可用”,我已经授予了这些权限并包含了库……我可以获取地图视图……它在地理编码器处抛出 IOException ……

I just added a catch IOException after the try and it solved the problem

我只是在尝试后添加了一个 catch IOException 并解决了问题

    catch(IOException ioEx){
        return null;
    }

回答by Manikanta Reddy

Geocoder coder = new Geocoder(this);
        List<Address> addresses;
        try {
            addresses = coder.getFromLocationName(address, 5);
            if (addresses == null) {
            }
            Address location = addresses.get(0);
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            Log.i("Lat",""+lat);
            Log.i("Lng",""+lng);
            LatLng latLng = new LatLng(lat,lng);
            MarkerOptions markerOptions = new MarkerOptions();
            markerOptions.position(latLng);
            googleMap.addMarker(markerOptions);
            googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(latLng,12));
        } catch (IOException e) {
            e.printStackTrace();
        }

回答by jay patoliya

public void goToLocationFromAddress(String strAddress) {
    //Create coder with Activity context - this
    Geocoder coder = new Geocoder(this);
    List<Address> address;

    try {
        //Get latLng from String
        address = coder.getFromLocationName(strAddress, 5);

        //check for null
        if (address != null) {

            //Lets take first possibility from the all possibilities.
            try {
                Address location = address.get(0);
                LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());

                //Animate and Zoon on that map location
                mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
                mMap.animateCamera(CameraUpdateFactory.zoomTo(15));
            } catch (IndexOutOfBoundsException er) {
                Toast.makeText(this, "Location isn't available", Toast.LENGTH_SHORT).show();
            }

        }


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