简体   繁体   English

GoogleMaps API无法获取当前的纬度和经度

[英]GoogleMaps API can't get current latitude and longitude

I'm trying to get the coordinates but without success. 我正在尝试获取坐标,但没有成功。 The result is 0 . 结果是0。 But when I write: 但是当我写:

googleMap.setMyLocationEnabled(true);

I can see the blue dot. 我可以看到蓝点。 I'm trying to get these values with this code: 我正在尝试通过以下代码获取这些值:

lat = googleMap.getMyLocation().getLatitude();
lng = googleMap.getMyLocation().getLongitude();

After that, lat and lng are 0. 之后, latlng为0。

My whole code: 我的整个代码:

public class GPS_maps extends Activity {
    // Google Map
    private GoogleMap googleMap;
    static Location currentLocation;
    static double lat , lng;
    TextView coordinates;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.map);
        coordinates = (TextView) findViewById(R.id.txt_coordinates);
        try {
            // Loading map
            initilizeMap();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void initilizeMap() {
        if (googleMap == null) {            
            googleMap = ((MapFragment) getFragmentManager().findFragmentById(R.id.map)).getMap();
            // googleMap.setMyLocationEnabled(true);
            lat = googleMap.getMyLocation().getLatitude();
            lng = googleMap.getMyLocation().getLongitude();
            coordinates.setText(String.valueOf(lat) +" , " +String.valueOf(lng));
            LatLng coordinate = new LatLng(lat, lng);
            CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
            googleMap.animateCamera(yourLocation);
            if (googleMap == null) {
                Toast.makeText(getApplicationContext(),
                    "Unable to create maps", Toast.LENGTH_SHORT)
                    .show();
            }
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
       initilizeMap();
    }}
}

I don't get any errors. 我没有任何错误。 Where is my mistake? 我的错误在哪里?

Try the following: 请尝试以下操作:

Remove static modifier from the declaration of lat, lan. 从lat,lan声明中删除静态修饰符。 Make sure you are sending in the correct syntax to setCoordiante. 确保您以正确的语法发送给setCoordiante。 To make sure the lat and lan are right, print them out right after you get them. 为确保lat和lan正确,请在获得它们之后立即将其打印出来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM