2015-08-11 4 views
0

У меня возникли проблемы с получением местоположения маркера, который я разместил на карте. После размещения маркера на карте я нажимаю кнопку, чтобы показать Toast, отображающий широту и долготу маркера, но приложение закрывает силу.Приобретайте маркер на Android с помощью Google maps api

это мой метод

public void markerLoc(View view) 
    { 
     LatLng lat = marker.getPosition(); 
     double lat1 = lat.latitude; 
     double lng1 = lat.longitude; 
     Toast.makeText(getBaseContext(),"lat: "+lat1+" & long: "+lng1,Toast.LENGTH_SHORT).show(); 
    } 

Basically i want to add a marker to the map and on pressing the button the marker's location is to be shown. If the marker is moved the new location is to be shown on pressing the button. 

Thanks in advance :) 

my activity 

public class Locate extends FragmentActivity implements LocationListener { 

    GoogleMap googleMap; 
    double latitude,longitude; 
    static int i=1; 
    GPSTracker gps; 
    Marker marker; 
    LatLng lat; 
    //Location location; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.locate); 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(getBaseContext()); 


     if(status!= ConnectionResult.SUCCESS){ 

      int requestCode = 10; 
      Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this, requestCode); 
      dialog.show(); 

     }else { 


      SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 


      googleMap = fm.getMap(); 


      googleMap.setMyLocationEnabled(true); 


      LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE); 


      Criteria criteria = new Criteria(); 


      String provider = locationManager.getBestProvider(criteria, true); 


      Location location = locationManager.getLastKnownLocation(provider); 

      if(location!=null){ 
       onLocationChanged(location); 
      } 
      locationManager.requestLocationUpdates(provider, 20000, 0, this); 
     } 


    } 



    @Override 
    public void onLocationChanged(Location location) { 

     TextView tvLocation = (TextView) findViewById(R.id.tv_location); 
     Toast.makeText(getBaseContext(),"lat: "+location.getLatitude()+"long: "+location.getLatitude(),Toast.LENGTH_LONG).show(); 

     latitude = location.getLatitude(); 

     longitude = location.getLongitude(); 


     LatLng latLng = new LatLng(latitude, longitude); 


     googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng)); 


     googleMap.animateCamera(CameraUpdateFactory.zoomTo(15)); 


     tvLocation.setText("Latitude:" + latitude + ", Longitude:"+ longitude); 



    } 


    @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 Dest(View view){ 
     if(i==1) { 
      i=0; 
      gps = new GPSTracker(Locate.this); 


      if(gps.canGetLocation()){ 

       double latitude = gps.getLatitude(); 
       double longitude = gps.getLongitude(); 


       Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show(); 
       marker = googleMap.addMarker(new MarkerOptions() 
         .position(new LatLng(latitude+0.0005, longitude+0.0005)) 
         .title("Your destination") 
         .draggable(true)); 
      }else{ 

       gps.showSettingsAlert(); 
      } 

     } 
     else 
      Toast.makeText(getBaseContext(),"You can add only one destination spot",Toast.LENGTH_SHORT).show(); 
    } 

    public void Clear(View view) 
    { 
     i=1; 
     googleMap.clear(); 
    } 

    public void markerLoc(View view) { 

     if (marker != null) { 
      lat = marker.getPosition(); 
      double lat1 = lat.latitude; 
      double lng1 = lat.longitude; 
      if(getBaseContext() != null) { 
       Toast.makeText(getBaseContext(), "lat: " + lat1 + " & long: " + lng1, Toast.LENGTH_SHORT).show(); 
      } 
     } 
    } 

} мой XML

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:orientation="vertical" android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <TextView 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:text="Location activity" 
     android:id="@+id/tv_location" 
     android:layout_gravity="center_horizontal" /> 
    <fragment xmlns:android="http://schemas.android.com/apk/res/android" 
     android:id="@+id/map" 
     android:layout_width="match_parent" 
     android:layout_height="500dp" 
     class="com.google.android.gms.maps.SupportMapFragment" /> 

    <RelativeLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent"> 


     <Button 
      style="?android:attr/buttonStyleSmall" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Add destination" 
      android:onClick="Dest" 
      android:id="@+id/dest" /> 

     <Button 
      style="?android:attr/buttonStyleSmall" 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="Clear" 
      android:id="@+id/clear" 
      android:onClick="Clear" 
      android:layout_alignParentTop="true" 
      android:layout_alignParentRight="true" 
      android:layout_alignParentEnd="true" /> 

     <Button 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" 
      android:text="MarkerLoc" 
      android:id="@+id/button" 
      android:onClick="markerLoc" 
      android:layout_alignParentBottom="true" 
      android:layout_centerHorizontal="true" /> 

    </RelativeLayout> 



</LinearLayout> 

Кнопка Dest добавляет новый маркер, который просто немного от текущего местоположения. Если я переместлю маркер в новое место, а затем нажмите кнопку markerLoc, местоположение не изменится, оно всегда показывает первое местоположение.

+0

проверка ли getBaseContext() равна нулю, используя, если (getBaseContext()! = NULL) {}, то же самое проверка маркера также, если (маркер! = NULL) {} – Rahul

ответ

0
public void markerLoc(View view) 
{ 
    if(marker != null) 
    { 
     LatLng lat = marker.getPosition(); 
     double lat1 = lat.latitude; 
     double lng1 = lat.longitude; 
     if(getBaseContext() != null) 
     { 
      Toast.makeText(getBaseContext(),"lat: "+lat1+" & long:  "+lng1,Toast.LENGTH_SHORT).show(); 
     } 
    } 
} 
+0

Это похоже на работу, но как я могу обновить позицию маркера? всякий раз, когда я нажимаю кнопку, он показывает мне ту же долготу и широту независимо от того, где я ее перемещаю. –

+0

не мог понять, пожалуйста, уточните свой вопрос?. Как я понимаю, вам нужно использовать слушателя. – Rahul

+0

Хотелось бы добавить производителя на карту. Если я нажму кнопку show_location, он должен показать мне широту и долготу маркера, который я только что добавил. Когда я пытаюсь переместить маркер, а затем нажмите кнопку show_location, значения новой широты и долготы не отображаются, вместо этого тост показывает предыдущее местоположение. Как обновить местоположение моего маркера? –

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