martes, 20 de agosto de 2013

Adding location to MapFragment

I am using Reverse Geocoding to get the location, after that, I am placing a marker in the location.

This code adds a location to the MapFragment:

public class AddressMapFragment extends MapFragment {
 
 LatLng location;
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
 }
 
 @Override
 public View onCreateView(LayoutInflater inflater, ViewGroup container,
   Bundle savedInstanceState) {
  View v =  super.onCreateView(inflater, container, savedInstanceState);
  
  Bundle args = getArguments();
  
  if(args!=null){
   String fulladdress = args.getString("fulladdress");
   new ReverseGeocoding().execute(fulladdress);
  }
  
  
  
  return v;
 }
 
 private void initMap(){
     UiSettings settings = getMap().getUiSettings();
     settings.setAllGesturesEnabled(false);
     settings.setMyLocationButtonEnabled(false);
     
     if(location!=null){

      getMap().moveCamera(CameraUpdateFactory.newLatLngZoom(location,16));
      getMap().addMarker(new MarkerOptions().position(location));
     }
 }
 
 public class ReverseGeocoding extends AsyncTask<String, Void, Void>{

  @Override
  protected Void doInBackground(String... params) {
   reverse_geocoding(params[0]);
   return null;
  }
  
  @Override
  protected void onPostExecute(Void result) {
   super.onPostExecute(result);
   
   initMap();
   
  }
  
 }
 
 public void reverse_geocoding(String fulladdress){
  
  Geocoder geo = new Geocoder(getActivity());
  try {
   List<Address> addresses = geo.getFromLocationName(fulladdress, 1);
   if(addresses.size()>0){
    Address address = addresses.get(0); 
    location = new LatLng(address.getLatitude(),address.getLongitude());
   }
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

No hay comentarios:

Publicar un comentario