【问题标题】:Unable to get address google maps v2无法获取地址谷歌地图 v2
【发布时间】:2014-01-07 12:18:52
【问题描述】:

我正在尝试使用 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)

【问题讨论】:

  • 你是否使用谷歌标记,如果用户点击你想获取地址的标记?
  • 是的。我正在使用正确获取 lat/lng 的 maponclickListener,但是当我尝试上面的代码时,它会遍历它并且它没有被处理。我试图调试它,但语句包括地理编码器和其余部分代码被跳过。请告诉我如何使它工作?在此先感谢
  • 如果你得到 lat long 值,而不仅仅是写 List
    地址 = geoCoder.getFromLocation(latitude ,longitude , 1); if (addresses.size() > 0) { for (int index = 0; index
  • 嗨 Subhalaxmi,变量 geoCoder 应该是什么样的?

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


【解决方案1】:

ADDRESS::FROM LAT N LONG IN MAP V2:

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

【讨论】:

  • List
    行中出现异常。更新了我的代码,请查看。再次感谢,
【解决方案2】:

按照此代码获取地址:

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

【讨论】:

  • 嗨 SHylu。我尝试了你的代码,但出现异常。我已经更新了上面的代码,请检查一下,让我知道问题出在哪里。再次感谢。
  • 您遇到的异常情况请告诉我。
  • 在列表
    行中出现异常。更新了我的代码。请看一下。
【解决方案3】:

使用这个。

地理编码器编码器;

    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.

    }

【讨论】:

  • 我使用了 Geocoder coder =new Geocoder(MainActivity.this, Locale.getDefault());对于您上面提到的编码器变量,但我得到服务不可用。我检查了 mapsv2 的文档。显然不支持地理编码器。有什么解决方法?再次感谢您调查问题
  • 在try语句中声明
  • 试过了,但说服务不可用,考虑使用 Google Geocoding API!!
【解决方案4】:

使用这个:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多