2014-01-07 2 views
1

Мое приложение отображает карту и автоматически переводит пользователя в свое текущее местоположение. Существует текстовое поле, которое позволяет пользователям вводить свое местоположение для отображения маркера по адресу, указанному в текстовой строке.Отображение текущего местоположения пользователя на картах Google только один раз

Когда я запускаю приложение, он правильно показывает пользователя, где они находятся. Когда я набираю новый адрес на карте, он показывает маркер в новом типизированном месте. Однако после этого он автоматически возвращает пользователя туда, где они находятся, и удаляет маркер из введенного пользователем местоположения.

Я полагаю, что onLocationChenaged срабатывает несколько раз. Кто-нибудь знает, какое решение найти местоположение пользователя только один раз, когда приложение запущено?

Это мой код:

public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
     { 
     if (view != null) 
     { 
      ViewGroup parent = (ViewGroup) view.getParent(); 
      if (parent != null) 
       parent.removeView(view); } 
     try 
     { 
      view = inflater.inflate(R.layout.fragment_map_view, container, false); 
     } 
     catch (InflateException e) 
     { /* map is already there, just return view as it is */ } 

     LocationManager lm = (LocationManager)getActivity().getSystemService(Context.LOCATION_SERVICE); 
     lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this); 

     map = ((SupportMapFragment)getFragmentManager().findFragmentById(R.id.map_fragment)).getMap(); 
     map.setMyLocationEnabled(true); 



     FragmentManager fm = getFragmentManager(); 
     FragmentTransaction ft = fm.beginTransaction(); 
     DateTimeFragment datetime=new DateTimeFragment(); 
     ft.add(R.id.datetime_container_map, datetime); 
     //SupportMapFragment mapFragment=null; 
     //if(mapFragment==null) 
      // mapFragment= (SupportMapFragment)fm.findFragmentById(R.id.map_fragment); 

     ft.commit(); 

     AutoCompleteTextView location= (AutoCompleteTextView)view.findViewById(R.id.location_map); 
     location.setAdapter(new PlacesAutoCompleteAdapter(getActivity(),R.layout.list_layout)); 
     location.setOnItemClickListener(this); 

     Spinner category=(Spinner)view.findViewById(R.id.category_query_map); 
     ArrayAdapter<CharSequence> adapterCategory = ArrayAdapter.createFromResource(this.getActivity().getBaseContext(),R.array.category_names, android.R.layout.simple_spinner_item); 
     adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
     category.setAdapter(adapterCategory); 
     category.setOnItemSelectedListener(this); 

     return view; 
     } 

    public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) 
    { 
     String address_text = (String) adapterView.getItemAtPosition(position); 
     Geocoder geocoder = new Geocoder(getActivity().getBaseContext()); 
     List<Address> addresses=null; 
     LatLng latlng; 
     MarkerOptions markerOptions; 

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

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

     // Clears all the existing markers on the map 
     map.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); 

      map.addMarker(markerOptions); 

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

    } 

    @Override 
    public void onLocationChanged(Location location) { 

     map.clear(); 
     MarkerOptions mp = new MarkerOptions(); 
     mp.position(new LatLng(location.getLatitude(), location.getLongitude())); 
     mp.title("my position"); 
     map.addMarker(mp); 
     map.animateCamera(CameraUpdateFactory.newLatLngZoom(
     new LatLng(location.getLatitude(), location.getLongitude()), 16)); 

     } 

     @Override 
     public void onProviderDisabled(String provider) { 
     // TODO Auto-generated method stub 

     } 

     @Override 
     public void onProviderEnabled(String provider) { 
     // TODO Auto-generated method stub 

     } 

     @Override 
     public void onStatusChanged(String provider, int status, Bundle extras) { 
     // TODO Auto-generated method stub 

     } 

     public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, 
       long arg3) { 
      // TODO Auto-generated method stub 
     } 

     public void onNothingSelected(AdapterView<?> arg0) { 
      // TODO Auto-generated method stub 
     } 

Кто-нибудь знает, почему после отображения маркера в набранный пользователем адрес, маркер автоматически обновляется до местоположения пользователя?

PS: Я также хотел бы знать, на стороне записки, если это хорошая практика, чтобы преобразовать строку в адрес с помощью Geocoder в shown..or я должен размещая это внутри AsyncTask

ответ

1

Может быть, ваш onLocationChanged() запускает и обновляет маркер до текущего местоположения?

Вы можете защититься от нескольких обновлений:

private Location mLocation = null; 

@Override 
public void onLocationChanged(Location location) { 

    if (mLocation == null) { 
     mLocation = location; 
     map.clear(); 
     MarkerOptions mp = new MarkerOptions(); 
     mp.position(new LatLng(location.getLatitude(), location.getLongitude())); 
     mp.title("my position"); 
     map.addMarker(mp); 
     map.animateCamera(CameraUpdateFactory.newLatLngZoom(
     new LatLng(location.getLatitude(), location.getLongitude()), 16)); 
    } 
    } 
+0

какая solution..how может я отобразить его только один раз – gazubi

+0

Вы можете сэкономить от объекта определения местоположения в переменной-члена, когда onLocationChanged пожаров в первый раз, и затем добавьте защиту внутри onLocationChanged(), чтобы не обновлять маркер, если местоположение уже установлено. – Eduard

+1

Я обновил ответ с помощью фрагмента кода – Eduard

Смежные вопросы