如何从LocationSettingsResponse方法中获取经纬度(latlng)?

huangapple go评论92阅读模式
英文:

how to get latlng from LocationSettingsResponse method?

问题

我正在尝试创建一个地图活动在地图上可以选择我的当前位置并在地图上的任何位置放置标记我尝试使用谷歌文档但我不明白如何从这个方法中获取经纬度是否有人对此有任何想法

LocationRequest locationRequest = LocationRequest.create();
locationRequest.setInterval(10000);
locationRequest.setFastestInterval(5000);
locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
        .addLocationRequest(locationRequest);
// ...

SettingsClient client = LocationServices.getSettingsClient(this);
Task<LocationSettingsResponse> task = client.checkLocationSettings(builder.build());

task.addOnSuccessListener(this, new OnSuccessListener<LocationSettingsResponse>() {
    @Override
    public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
        // 所有定位设置均满足。客户端可以在此处初始化定位请求。
        // ...
    }
});
英文:

I am Trying to make a map activity that i can choose my current location and make a marke on any location in the map,, i tried to use google documentation but i didn't understand how can i get latlng from this method any one have and idea about that !

LocationRequest locationRequest = LocationRequest.create();
    locationRequest.setInterval(10000);
    locationRequest.setFastestInterval(5000);
    locationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

    LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder()
            .addLocationRequest(locationRequest);
    // ...

    SettingsClient client = LocationServices.getSettingsClient(this);
    Task&lt;LocationSettingsResponse&gt; task = client.checkLocationSettings(builder.build());

    task.addOnSuccessListener(this, new OnSuccessListener&lt;LocationSettingsResponse&gt;() {
        @Override
        public void onSuccess(LocationSettingsResponse locationSettingsResponse) {
            // All location settings are satisfied. The client can initialize
            // location requests here.
            // ...
            

        }
    });

答案1

得分: 0

对于您的问题请创建以下函数

public void centreMapOnLocation(Location location, String title) {

    if (location != null) {
        LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());

        mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
    }
}

在 onMapReady 函数中添加以下代码

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

    mMap.setOnMapLongClickListener(this);
    mMap.clear();

    locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    locationListener = new LocationListener() {
        @Override
        public void onLocationChanged(Location location) {
            centreMapOnLocation(location, "您的位置");
        }

        @Override
        public void onStatusChanged(String s, int i, Bundle bundle) {

        }

        @Override
        public void onProviderEnabled(String s) {

        }

        @Override
        public void onProviderDisabled(String s) {

        }
    };

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
        Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        centreMapOnLocation(lastKnownLocation, "您的位置");

    } else {
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
    }
}

在 onMapLongClick 函数中

Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());

String address = "";

try {

    List<Address> listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);

    if (listAddresses != null && listAddresses.size() > 0) {

        if (listAddresses.get(0).getThoroughfare() != null) {
            address += listAddresses.get(0).getThoroughfare() + " ";
        }
        address += listAddresses.get(0).getSubThoroughfare() + " ";

    }

} catch (Exception e) {
    e.printStackTrace();
}

if (address.equals("")) {
    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm dd-MM-yyyy");
    address += sdf.format(new Date());

}
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
SharedPreferences sharedPreferences = this.getSharedPreferences("com.luv.memorableplaces", Context.MODE_PRIVATE);

try {

    ArrayList<String> lat = new ArrayList<String>();
    ArrayList<String> lng = new ArrayList<String>();

    for (LatLng coord : MainActivity.locations) {

        lat.add(Double.toString(coord.latitude));
        lng.add(Double.toString(coord.longitude));

        sharedPreferences.edit().putString("latitudes", ObjectSerializer.serialize(lat)).apply();
        sharedPreferences.edit().putString("longitudes", ObjectSerializer.serialize(lng)).apply();
    }

    sharedPreferences.edit().putString("places", ObjectSerializer.serialize(MainActivity.places)).apply();

} catch (Exception e) {
    e.printStackTrace();
}

Toast.makeText(this, "位置已保存", Toast.LENGTH_SHORT).show();

这也将帮助您保存先前的位置尝试一下应该可以工作
英文:

For your problem create a function like follows :

 public void centreMapOnLocation(Location location, String title){
if (location != null) {
LatLng userLocation = new LatLng(location.getLatitude(), location.getLongitude());
mMap.addMarker(new MarkerOptions().position(userLocation).title(title));
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userLocation, 15));
}
}

In onMapReady function add the following code :

 @Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
mMap.setOnMapLongClickListener(this);
mMap.clear();
locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
locationListener = new LocationListener() {
@Override
public void onLocationChanged(Location location) {
centreMapOnLocation(location, &quot;Your Location&quot;);
}
@Override
public void onStatusChanged(String s, int i, Bundle bundle) {
}
@Override
public void onProviderEnabled(String s) {
}
@Override
public void onProviderDisabled(String s) {
}
};
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0 , 0, locationListener);
Location lastKnownLocation = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
centreMapOnLocation(lastKnownLocation, &quot;Your Location&quot;);
}else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION},1);
}
}

In the onMapLongClick :

Geocoder geocoder = new Geocoder(getApplicationContext(), Locale.getDefault());
String address = &quot;&quot;;
try {
List&lt;Address&gt; listAddresses = geocoder.getFromLocation(latLng.latitude, latLng.longitude, 1);
if(listAddresses != null &amp;&amp; listAddresses.size() &gt; 0){
if (listAddresses.get(0).getThoroughfare() != null){
address += listAddresses.get(0).getThoroughfare() + &quot; &quot;;
}
address += listAddresses.get(0).getSubThoroughfare() + &quot; &quot;;
}
}catch (Exception e){
e.printStackTrace();
}
if (address.equals(&quot;&quot;)){
SimpleDateFormat sdf = new SimpleDateFormat(&quot;HH:mm dd-MM-yyyy&quot;);
address += sdf.format(new Date());
}
mMap.addMarker(new MarkerOptions().position(latLng).title(address));
SharedPreferences sharedPreferences = this.getSharedPreferences(&quot;com.luv.memorableplaces&quot;, Context.MODE_PRIVATE);
try {
ArrayList&lt;String&gt; lat = new ArrayList&lt;String&gt;();
ArrayList&lt;String&gt; lng = new ArrayList&lt;String&gt;();
for (LatLng coord : MainActivity.locations){
lat.add(Double.toString(coord.latitude));
lng.add(Double.toString(coord.longitude));
sharedPreferences.edit().putString(&quot;latitudes&quot;, ObjectSerializer.serialize(lat)).apply();
sharedPreferences.edit().putString(&quot;longitudes&quot;, ObjectSerializer.serialize(lng)).apply();
}
sharedPreferences.edit().putString(&quot;places&quot;, ObjectSerializer.serialize(MainActivity.places)).apply();
}catch (Exception e){
e.printStackTrace();
}
Toast.makeText(this, &quot;Location Saved&quot;, Toast.LENGTH_SHORT).show();

This will also help you save the previous location. Try it out, it should work.

huangapple
  • 本文由 发表于 2020年8月26日 21:17:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/63598528.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定