当我点击谷歌地图中显示的标记时,如何获得纬度和经度

时间:2016-10-21 13:59:04

标签: android google-maps

我已经实现了一种从搜索栏搜索地点的方法,应用程序显示标记绝对正常。但是在我单击显示的标记后,不会显示任何Toast消息。有人可以告诉我如何实现相同的。 这是我使用的代码,但是当我点击标记时,我无法获得纬度和经度。

import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

import java.io.IOException;
import java.util.List;

public class SearchMaps extends FragmentActivity implements OnMapReadyCallback,GoogleMap.OnMarkerClickListener {
private GoogleMap mMap;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_search_maps);
    // Obtain the SupportMapFragment and get notified when the map is ready to be used.
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
}

public void onSearch(View view) {
    EditText location_tf = (EditText) findViewById(R.id.TSearch);
    String location = location_tf.getText().toString();
    List<Address> addressList = null;

    if (location != null || !location.equals("")) {
        Geocoder geocoder = new Geocoder(this);
        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.getLongitude());
        mMap.clear();
        mMap.addMarker(new MarkerOptions().position(latLng).title("Marker")
                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        mMap.animateCamera(CameraUpdateFactory.newLatLng(latLng));
    }
}


@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;


}
@Override
public boolean onMarkerClick(Marker marker) {
    LatLng position = marker.getPosition();
    Toast.makeText(
            SearchMaps.this,
            "Lat " + position.latitude + " " + "Long " + position.longitude,Toast.LENGTH_LONG).show();
    return false;
}
}

2 个答案:

答案 0 :(得分:1)

只需在mMap.setOnMarkerClickListener(this);方法的末尾添加onMapReady

答案 1 :(得分:0)

您是否首先尝试使用Log.d?因为Toast需要上下文,有时您需要使用Toast

runOnUIThread附加到用户界面