无法获取地址谷歌地图v2

时间:2013-10-15 23:32:06

标签: android google-maps google-maps-android-api-2

我正在尝试使用lat,lng来获取地址 但它没有工作粘贴下面的代码。 我真的很感激任何帮助 我一直都处于异常状态而不是错误的价值吗?

先谢谢。

       googleMap.setOnMapClickListener((OnMapClickListener) new OnMapClickListener() {

            @Override
            public void onMapClick(LatLng point) {
                // TODO Auto-generated method stub



                  final LatLng pt = point;

                  marker2 = googleMap.addMarker(new MarkerOptions()
                  .position(pt)
                  .icon(BitmapDescriptorFactory.fromResource(R.drawable.ic_launcher)));



                    final ProgressDialog progressDialog = ProgressDialog.show(
                            MainActivity.this,
                            "Searching Location....", "Please wait....");


                    new Thread(new Runnable(){
                        public void run(){
                            try {




                                    Toast.makeText(getBaseContext(), GeocoderUtil.getAddress(marker2.getPosition(), MainActivity.this), 5).show();


                                }catch(Exception e)
                                {


                                    runOnUiThread(new Runnable() {
                                        public void run() {

                                            progressDialog.dismiss(); 

                                            Toast.makeText(getBaseContext(),"error.", 5).show();
                                        }
                                    });


                                }}}

                    ).start();

例外:

FATAL EXCEPTION: main
 java.lang.NullPointerException
    at com.maps.maps.MainActivity$1.onMapClick(MainActivity.java:442)
    at com.google.android.gms.maps.GoogleMap$.onMapClick(Unknown Source)
    at com.google.android.gms.maps.internal.h$a.onTransact(Unknown Source)
    at android.os.Binder.transact(Binder.java:297)
    at bor.a(SourceFile:93)
    at maps.af.q.b(Unknown Source)
    at maps.ap.bo.b(Unknown Source)
    at maps.ap.bk.onSingleTapConfirmed(Unknown Source)
    at maps.bt.g.onSingleTapConfirmed(Unknown Source)
    at maps.bt.i.handleMessage(Unknown Source)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:154)
    at android.app.ActivityThread.main(ActivityThread.java:4945)
    at java.lang.reflect.Method.invokeNative(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:511)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
    at dalvik.system.NativeStart.main(Native Method)

4 个答案:

答案 0 :(得分:10)

ADDRESS ::来自地图V2的LAT N长期:

    String address = "";
     Geocoder geoCoder = new Geocoder( getBaseContext(), Locale.getDefault());
         try {
           List<Address> addresses = geoCoder.getFromLocation(latitude ,longitude , 1);
           if (addresses.size() > 0) 
              {
              for (int index = 0; 
              index < addresses.get(0).getMaxAddressLineIndex(); index++)
               address += addresses.get(0).getAddressLine(index) + " "; }
                           }
         catch (IOException e) {        
             e.printStackTrace();
           }   
 googleMap_v2.animateCamera(CameraUpdateFactory.zoomTo(15));
          current_location.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude );
          current_address.setText("current Address :" + address ); 
          googleMap_v2.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("current status")); 
        }}

答案 1 :(得分:3)

  

请按照以下代码获取地址:

            final TextView address = (TextView) infoWindow.findViewById(R.id.Address);
        address.setText(GeoCoderUtil.getAddress(marker.getPosition(), CurrentActivity.this));

    GeoCoderUtil.java:


    import java.io.IOException;
    import java.text.DecimalFormat;
    import java.util.List;

    import android.content.Context;
    import android.location.Address;
    import android.location.Geocoder;
    import android.location.Location;
    import android.util.Log;
    import android.widget.Toast;

    import com.google.android.gms.maps.model.LatLng;

    public class GeoCoderUtil {

        public static String getAddress(LatLng latLng, Context context) {
            Geocoder geocoder = new Geocoder(context);
            double latitude = latLng.latitude;
            double longitude = latLng.longitude;

            String address = "";

            try {
    Log.i("Address Info","Address based opn geocoder");
                List<Address> addresses = geocoder.getFromLocation(latitude,
                        longitude, 1);

                if (addresses != null && !addresses.isEmpty()) {
                    Address returnedAddress = addresses.get(0);
                    StringBuilder strReturnedAddress = new StringBuilder();
                    int addressLineIndex = returnedAddress.getMaxAddressLineIndex();

                    int addressLinesToShow = 2;
    //              To get address in limited lines
                    if (addressLineIndex < 2) {
                        addressLinesToShow = addressLineIndex;
                    }
                    for (int p = 0; p < addressLinesToShow; p++) {
                        strReturnedAddress
                                .append(returnedAddress.getAddressLine(p)).append(
                                        "\n");
                    }
                    address = strReturnedAddress.toString();
                } else {
                    address = "Address not available";

                }
            } catch (IOException e) {
                e.printStackTrace();
                address = "Address not available";
                Log.e("Address not found","Unable to get Address in info window");
            }
            return address;
        }

        public static String getDistanceByUnit(double startLatitude, double startLongitude, double endLatitude, double endLongitude) {
            float[] distance = new float[1];
            Log.i("Distance","Distance from source to end");
            Location.distanceBetween(startLatitude, startLongitude, endLatitude,
                    endLongitude, distance);
            String distanceByUnit = "Not Available";

            DecimalFormat d = new DecimalFormat("0.00");
            if (distance[0] > 999.99) {
                distance[0] = distance[0] / 1000;
                distanceByUnit = String.valueOf(d.format(distance[0])) + " Km";
            } else {
                distanceByUnit = String.valueOf(d.format(distance[0])) + " m";
            }
            return distanceByUnit;
        }
    }

答案 2 :(得分:0)

使用此功能。

Geocoder编码器;

    public String PointToLoc(LatLng pos )
{
String address="";
try {

List<Address>addresses=coder.getFromLocation(pos.latitude,pos.longitude,1);

if (addresses.size()>0)
{

for (int index=0;index<addresses.get(0).getMaxAddressLineIndex();index++)

            address += addresses.get(0).getAddressLine(index)+"";

        Log.d("Address",""+ address); //full address
        Log.d("Address1",""+  addresses.get(0).getLocality()); //city
        Log.d("Address2",""+  addresses.get(0).getSubLocality()); //area

     }


    }
 catch (IOException e)
        {        
          e.printStackTrace();
        }   
    return address;
}
    @Override
  public void onInfoWindowClick(Marker marker) {
  String cur_address=PointToLoc(marker.getPosition());
  //Toast the above string.You will get it.

    }

答案 3 :(得分:0)

使用此:

 // An AsyncTask class for accessing the GeoCoding Web Service
    private class GeocoderTask extends AsyncTask<String, Void, List<Address>>{

        @Override
        protected List<Address> doInBackground(String... locationName) {
            // Creating an instance of Geocoder class
            Geocoder geocoder = new Geocoder(getBaseContext());
            List<Address> addresses = null;

            try {
                // Getting a maximum of 3 Address that matches the input text
                addresses = geocoder.getFromLocationName(locationName[0], 3);
            } catch (IOException e) {
                e.printStackTrace();
            }
            return addresses;
        }

        @Override
        protected void onPostExecute(List<Address> addresses) {

            if(addresses==null || addresses.size()==0){
                Toast.makeText(getBaseContext(), "No Location found", Toast.LENGTH_SHORT).show();
            }

            // Clears all the existing markers on the map
            googleMap.clear();

            // Adding Markers on Google Map for each matching address
            for(int i=0;i<addresses.size();i++){

                Address address = (Address) addresses.get(i);

                // Creating an instance of GeoPoint, to display in Google Map
                latLng = new LatLng(address.getLatitude(), address.getLongitude());

                String addressText = String.format("%s, %s",
                address.getMaxAddressLineIndex() > 0 ? address.getAddressLine(0) : "",
                address.getCountryName());

                markerOptions = new MarkerOptions();
                markerOptions.position(latLng);
                markerOptions.title(addressText);

                googleMap.addMarker(markerOptions);

                // Locate the first location
                if(i==0)
                    googleMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
            }
        }