如何从地址中获取纬度和经度?

122

我想在Google Maps中显示某个地址的位置。

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


我曾经遇到同样的问题,这里是我的解决方案 https://dev59.com/QFzUa4cB1Zd3GeqP6L9s#19170557 - Bruno Pinto
10个回答

148
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;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return null;
}

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


1
它抛出了“java.io.IOException服务不可用”的异常。 - Kandha
4
访问该服务需要正确的权限。 <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> <uses-permission android:name="android.permission.INTERNET" /> - Flo
1
我已经授予了这些权限并包含了库...我可以获取地图视图...但在geocoder处抛出了IOException。 - Kandha
@Mr.Hyde,您使用的API版本是哪个? - ud_an
6
请查看下面@NayAneshGupte的答案,我认为新库中没有GeoPoint类。 相反,可以使用LatLng。https://dev59.com/_3A65IYBdhLWcg3w5y_B#27834110 - user2968401
显示剩余10条评论

93

Ud_an的解决方案使用了更新的API。

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

必须注意:

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

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

更新:如果您的目标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;
}

2
谢谢,这个方法对我有用,上面的解决方案不起作用。 - Rizwan Sohaib
1
在实例化Geocoder时,您应该传递上下文。例如:Geocoder coder = new Geocoder(this); 或者 new Geocoder(getApplicationContext),而不是像答案中所述使用getActivity()。 - The_Martian
1
@Quantumdroid 上面的代码是在片段中编写的。否则你是完全正确的。这是上下文。 - Nayanesh Gupte
2
优美而干净的解决方案。没有一个答案提到Geocoder使用同步访问,因此强烈建议将其放入后台服务中以避免阻塞UI。 - The_Martian
1
很好的解决方案。当输入无效的地址/邮编时,将调用IOException。您可以通过一个简单的 if(address.size() <1){//show a Toast}else{//put rest of code here} 来避免这个错误。 - grantespo
显示剩余3条评论

53

如果您想将您的地址放在Google地图上,那么简单的方法是使用以下内容:

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

如果您需要从地址获取经纬度,请使用Google Place API,并按照以下步骤:

创建一个方法,返回一个带有HTTP调用响应的JSONObject,如下所示:

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

现在将该 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;
    }

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


1
不幸的是,这个解决方案在某些移动运营商的移动连接中无法使用:请求总是返回 OVER_QUERY_LIMIT。这些移动运营商使用NAT过载,将同一个IP分配给多个设备... - Umberto
@UmbySlipKnot,你能详细解释一下OVER_QUERY_LIMIT吗?那是什么?谢谢。 - sfmirtalebi

7
以下代码将适用于Google API V2:
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

其中,address是你想要转换为经纬度的字符串(格式为:街道地址 城市 州 邮政编码)。


1
 yourButton.setOnClickListener {
            AppUtil.hideSoftKeyboard(this)
            if (yourEdittext.text.isNotEmpty()) {
                var location: LatLng? = null
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
                    val coder = Geocoder(this@WeatherMapActivity)
                    coder.getFromLocationName(yourEdittext.text.toString(), 5,object :Geocoder.GeocodeListener{
                        override fun onGeocode(addresses: MutableList<Address>) {
                            addresses.forEach {
                                //do your work android 13
                                Log.d("locationFRR", "onGeocode: ${it.latitude}")
                                Log.d("locationFRR", "onGeocode: ${it.longitude}")
                                location = LatLng(it.latitude, it.longitude)
                            }

                            location?.let {
                                Log.d("locationFRR", "onCreate: ${it.latitude}")
                                Log.d("locationFRR", "onCreate: ${it.longitude}")
                                getWeather(it.latitude.toString(), it.longitude.toString())
                            }
                        }

                        override fun onError(errorMessage: String?) {
                            super.onError(errorMessage)
                            Log.d("locationFRR", "onError: $errorMessage")
                            Toast.makeText(
                                this@WeatherMapActivity,
                                "City not found",
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    })

                } else {
                    //less than Android 13
                    //using Coroutine to avoid ANRs

                    GlobalScope.launch(Dispatchers.IO) {
                        location =
                            getLocationFromAddress(yourEdittext.text.toString())
                        withContext(Dispatchers.Main) {
                            location?.let {
                                Log.d("locationFRR", "onCreate: ${it.latitude}")
                                Log.d("locationFRR", "onCreate: ${it.longitude}")
                                getWeather(it.latitude.toString(), it.longitude.toString())
                            } ?: run {
                                Toast.makeText(
                                    this@WeatherMapActivity,
                                    "City not found",
                                    Toast.LENGTH_SHORT
                                ).show()
                            }
                        }
                    }

                }

            }
        }

 private fun getLocationFromAddress(strAddress: String): LatLng? {
        val coder = Geocoder(this)
        var p1: LatLng? = null
        try {
            val address: MutableList<Address>? = coder.getFromLocationName(strAddress, 5)

            address?.let {
                if (it.size > 0) {


                    address[0].let { add ->
                        p1 = LatLng(
                            (add.latitude),
                            (add.longitude)
                        )
                    }

                }

                Log.d("locationFRR", "getLocationFromAddress: $p1")
            }

        } catch (e: IOException) {
            e.printStackTrace()
            Log.d("locationFRR", "getLocationFromAddress: ${e.message}")
        }
        return p1
    }
 

1

对于上面的Kandha问题的答案:

它抛出“java.io.IOException服务不可用”的异常,我已经授予了这些权限并包含了库...我可以获取地图视图...但在geocoder处抛出了IOException异常...

我只是在try后面添加了一个catch IOException,问题就解决了。

    catch(IOException ioEx){
        return null;
    }

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

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

1
那个空值检查没有起到任何作用。 - charles-allen

0
public LatLang getLatLangFromAddress(String strAddress){
    Geocoder coder = new Geocoder(this, Locale.getDefault());
    List<Address> address;
    try {
        address = coder.getFromLocationName(strAddress,5);
        if (address == null) {
                return new LatLang(-10000, -10000);
            }
            Address location = address.get(0);
            return new LatLang(location.getLatitude(), location.getLongitude());
        } catch (IOException e) {
            return new LatLang(-10000, -10000);
        }
    }            

LatLang 在这种情况下是一个普通的 Java 对象类。

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 权限不是必需的。


-1

我知道现在回答这个10年前的问题已经太晚了,在2021年。以下的代码是完全可用的代码。

activity_main.xml 的代码:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Enter Address"
    android:id="@+id/addressTV"
    android:textAppearance="?android:attr/textAppearanceMedium"
    android:layout_alignParentStart="true" />

<EditText
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:id="@+id/addressET"
    android:layout_alignParentTop="true"
    android:layout_toEndOf="@+id/addressTV"
    android:singleLine="true"
    android:hint="1600 Pennsylvania Ave NW Washington DC 20502" />

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Show Lat/Long"
    android:id="@+id/addressButton"
    android:layout_below="@+id/addressTV"
    android:layout_toEndOf="@+id/addressTV"
    android:layout_marginTop="50dp" />

<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceLarge"
    android:text=""
    android:id="@+id/latLongTV"
    android:layout_centerVertical="true"
    android:layout_toEndOf="@+id/addressTV" />

AndroidManifest.xml 给予以下权限:

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

MainActivity.java

public class MainActivity extends Activity {
Button addressButton;
TextView addressTV;
TextView latLongTV;
EditText addressET;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);

    addressET = findViewById(R.id.addressET);
    addressTV = (TextView) findViewById(R.id.addressTV);
    latLongTV = (TextView) findViewById(R.id.latLongTV);

    addressButton = (Button) findViewById(R.id.addressButton);
    addressButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {


            String address = addressET.getText().toString();

            GeocodingLocation locationAddress = new GeocodingLocation();
            locationAddress.getAddressFromLocation(address,
                    getApplicationContext(), new GeocoderHandler());


           
        }
    });

}

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String address;
        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                address = bundle.getString("address");
                break;
            default:
                address = null;
        }
        latLongTV.setText(address);
    }
}

}

GeocodingLocation.java

public class GeocodingLocation {



public static void getAddressFromLocation(String locationAddress, Context context,  Handler handler) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            Geocoder geocoder = new Geocoder(context, Locale.getDefault());
            String result = null;

            try {
                List addressList = geocoder.getFromLocationName(locationAddress,1);
                if (addressList != null && addressList.size() > 0){
                    Address address = (Address) addressList.get(0);
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append(address.getLatitude()).append("\n");
                    stringBuilder.append(address.getLongitude()).append("\n");
                    result = stringBuilder.toString();
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                Message message = Message.obtain();
                message.setTarget(handler);
                if (result != null){
                    message.what = 1;
                    Bundle bundle = new Bundle();
                    result = "Address   :   "+locationAddress+
                            "\n\n\nLatitude and longitude\n"+result;
                    bundle.putString("address",result);
                    message.setData(bundle);
                }
                message.sendToTarget();
            }
        }
    };
    thread.start();
}

}


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接