如何在安卓设备上通过地址获取纬度和经度?

5
3个回答

4
private void getFromLocation(String address)
    {
          double latitude= 0.0, longtitude= 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));

                latitude=p.getLatitudeE6()/1E6;
                longtitude=p.getLongitudeE6()/1E6;


                }
        }
        catch(Exception ee)
        {

        }
    }
}

这里没有 GeoPoint 类。 - William Willi
这是旧答案。您需要在build.gradle中添加Google地图API。 - Kamal
或者您可以直接从地址对象中获取纬度和经度。 - Kamal

2

这将为您提供(遍历)地址字符串的所有匹配项。如果您只想要第一个匹配项,请确保address.size()大于0,然后取address.get(0);

在我的使用中,我获取所有匹配项,并将它们显示为选项。然后用户单击其中一个选项,选择该GPS位置。

Geocoder geocoder = new Geocoder(getBaseContext());  
List<Address> addresses;
try {
   addresses = geocoder.getFromLocationName("Example StreeT, UK, DNFE", 20);

   for(int i = 0; i < addresses.size(); i++) { // MULTIPLE MATCHES

     Address addr = addresses.get(i);

     double latitude = addr.getLatitude();
     double longitude = addr.getLongitude(); // DO SOMETHING WITH VALUES

   }

}

谢谢您的快速回复。我会尝试这个。 - diordna

2

从下面的代码中,您可以了解到:

private void GetLatitudeAndLongitude() {
    geocoder = new Geocoder(mContext, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocationName(txtLocation.getText().toString().trim().toLowerCase(), 1);
        if (addresses.size() > 0) {
            homeInfoModel.setLalitude(String.valueOf(addresses.get(0).getLatitude()));
            homeInfoModel.setLongitude(String.valueOf(addresses.get(0).getLongitude()));
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
}

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