1

我正在使用谷歌地图V2。我想使用geocoder找到位置,但是getFromLocationName()它返回空值,我无法找到原因。只要看看我的代码并建议我,我该怎么办?为什么Geocoder.getFromLocationName返回null?

EditText sLocation = (EditText) v.findViewById(R.id.editText1); 
       String location = sLocation.getText().toString(); 

       List<android.location.Address> addressList= null; 

       if (location != null || !location.equals("")) { 
        Geocoder geocoder = new Geocoder(getActivity().getApplicationContext()); 
        try { 
         addressList = geocoder.getFromLocationName(location, 1); 

        } catch (IOException e) { 
         e.printStackTrace(); 
        } 


        android.location.Address address = addressList.get(0); 
        LatLng latlng = new LatLng(address.getLatitude(), address.getLatitude()); 
        gMap.addMarker(new MarkerOptions().position(latlng).title("Marker")); 
        gMap.animateCamera(CameraUpdateFactory.newLatLng(latlng)); 

       } 
+1

入住这太问题[4567216](http://stackoverflow.com/questions/4567216/geocoder-getfromlocationname-returns-only -null)和[15182853](http://stackoverflow.com/questions/15182853/android-geocoder-getfromlocationname-always-returns-null)如果它可以帮助你。 – KENdi

+0

@KENdi,我解决了我的问题。请看我下面的答案。 –

回答

1

我得到空值表格getFromLocationName()。因为,我的addressList从位置获得“空”值。当我宣布我EditTextonClick方法则getFromLocationName()回到我正确的值是这样的:

sButton =(Button) v.findViewById(R.id.generalId); 
sButton.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       EditText sLocation = (EditText)getActivity().findViewById(R.id.editText1); 
       location = sLocation.getText().toString(); 

       List<android.location.Address> addressList= null; 

       if (location != null || location.length()>0) { 
        Geocoder geocoder = new Geocoder(getActivity().getApplicationContext()); 
        try { 
         addressList = geocoder.getFromLocationName(location, 1); 

        } catch (IOException e) { 

          e.printStackTrace(); 
        } 

        android.location.Address address = addressList.get(0); 
        String locality = address.getLocality(); 
        Toast.makeText(getActivity(), locality, Toast.LENGTH_LONG).show(); 
        double latitude = address.getLatitude(); 
        double longitude = address.getLongitude(); 
        LatLng latLng = new LatLng(latitude, longitude); 
        gMap.addMarker(new MarkerOptions().position(latLng).title("Marker")); 
        gMap.animateCamera(CameraUpdateFactory.newLatLng(latLng)); 

       } 

      } 
     });