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

时间:2010-08-26 11:31:34

标签: android google-maps google-geocoder

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

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

9 个答案:

答案 0 :(得分:127)

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

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

答案 1 :(得分:64)

Ud_an的解决方案,更新了API&#39>

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

<强>强制性

<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 :(得分:51)

如果您想将地址放在谷歌地图中,​​那么可以轻松使用以下

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

OR

如果您需要从您的地址获得很长的时间,请使用 Google Place Api

使用 HTTP Call 的响应创建一个返回 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;
    }

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

答案 3 :(得分:6)

以下代码适用于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

其中address是要转换为LatLng的String(123 Testing Rd City State zip)。

答案 4 :(得分:3)

这是您可以找到我们点击地图的纬度和经度的方法。

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

效果很好。

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

答案 5 :(得分:1)

上面对Kandha问题的回答:

  

它抛出&#34; java.io.IOException服务不可用&#34;   我已经给了这些权限并包含了库...我可以获得地图视图...它会在地理编码器中抛出IOException ...

我在尝试后添加了一个catch IOException,它解决了问题

    catch(IOException ioEx){
        return null;
    }

答案 6 :(得分: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();
        }

答案 7 :(得分: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在这种情况下是pojo类。

不需要

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

答案 8 :(得分:0)

我知道我在 2021 年对 10 岁问题的贡献为时已晚。以下代码是完整的工作代码。

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

}

相关问题