【问题标题】:Fetch the current location of the user获取用户的当前位置
【发布时间】:2017-07-04 12:54:55
【问题描述】:

我需要在我的代码中进行哪些更改以使其获取用户的当前位置而不是预定义的纬度和经度?

这是我的代码:

package com.example.safwan.mypersonal;

import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
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.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {

    private GoogleMap mMap;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_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);
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        // Add a marker in Sydney and move the camera
        LatLng cannaughtplace = new LatLng(28.6315,77.2167);
        mMap.addMarker(new MarkerOptions()
            .position(cannaughtplace)
            .title("Marker in Cannught place"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(cannaughtplace));
    }
}

【问题讨论】:

  • 您需要进行的第一个更改是格式化您在此处发布的代码。没有人喜欢读这个。

标签: android


【解决方案1】:
  locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    try {
        location = locationManager.getLastKnownLocation(provider);
    }
    catch (Exception e)
    {

    }
    if(location==null) {
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    }

    if (location != null) {
        double lat = location.getLatitude();
        double longg = location.getLongitude();
        mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(lat,longg) , 14.0f) );
        startService(new Intent(MainActivity.this, MyService.class));
        ismarkervisible = true;
    } else {
        Toast.makeText(MainActivity.this, "Device Failed To Fetch Lat Long", Toast.LENGTH_LONG).show();
    }

【讨论】:

  • 试试上面的方法
猜你喜欢
  • 2011-07-20
  • 2023-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-11
  • 2022-01-18
相关资源
最近更新 更多