web-dev-qa-db-ja.com

androidでMAPBOXの現在の場所を取得する方法

アプリケーションでMAPBOXを使用しているため、現在の緯度と経度を取得する方法がわかりません。この方法で現在の場所を取得しましたが、nullオブジェクト参照が表示されています。問題の解決にご協力ください

     mapView = (MapView)view. findViewById(R.id.mapView);
    mapView.setStyleUrl(Style.MAPBOX_STREETS);
    mapView.onCreate(savedInstanceState);

    //Add a mapBoxMap
    mapView.getMapAsync(new OnMapReadyCallback() {
        @Override
        public void onMapReady(MapboxMap mapboxMap) {
            mapboxMap.setMyLocationEnabled(true);
            // Set the Origin waypoint to the devices location
            Position Origin = Position.fromCoordinates(mapboxMap.getMyLocation().getLongitude(), mapboxMap.getMyLocation().getLatitude());

            Log.i("RR","mapboxMap.getMyLocation();"+Origin);
           // Log.i("RR","mapboxMap.getMyLocation();"+mapboxMap.getMyLocation().getLongitude());
            mapboxMap.getUiSettings().setZoomControlsEnabled(true);
            mapboxMap.getUiSettings().setZoomGesturesEnabled(true);
            mapboxMap.getUiSettings().setScrollGesturesEnabled(true);
            mapboxMap.getUiSettings().setAllGesturesEnabled(true);


        }

    });
6
kalai vani

mapboxMap.setMyLocationEnabled(true);deprecatedになりました。

このように緯度と経度を取得するには、locationEngineを使用する必要があります

_    locationEngine = new LostLocationEngine(MainActivity.this);
    locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
    locationEngine.setInterval(5000);
    locationEngine.activate();
    Location lastLocation = locationEngine.getLastLocation();
_

lastLocation.getLatitude()lastLocation.getLongitude()を使用

4
Jaganath

1日の検索を費やした後、結果が得られました。これは、MapBoxユーザーの現在地を取得するための完全なコードです。主な活動:

import Android.Manifest;
import Android.annotation.SuppressLint;
import Android.content.pm.PackageManager;
import Android.location.Location;
import Android.support.annotation.NonNull;
import Android.support.v4.app.ActivityCompat;
import Android.support.v7.app.AppCompatActivity;
import Android.os.Bundle;

import com.mapbox.Android.core.location.LocationEngine;
import com.mapbox.Android.core.location.LocationEngineListener;
import com.mapbox.Android.core.location.LocationEnginePriority;
import com.mapbox.Android.core.location.LocationEngineProvider;
import com.mapbox.Android.core.permissions.PermissionsListener;
import com.mapbox.Android.core.permissions.PermissionsManager;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;

import Java.util.List;

public class Main2Activity extends AppCompatActivity implements OnMapReadyCallback, LocationEngineListener, PermissionsListener {
    private MapView mapView;
    private MapboxMap map;
    LocationEngine locationEngine;
    LocationLayerPlugin locationLayerPlugin;
    PermissionsManager permissionsManager;
    Location originLayout;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Mapbox.getInstance(this, "YOUR_MAPBOX_KEY");
        setContentView(R.layout.activity_main2);
        mapView = (MapView) findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        mapView.getMapAsync(this);
    }

    @Override
    public void onMapReady(MapboxMap mapboxMap) {
       /* LocationPluginActivity.this.map = map;
        enableLocationPlugin();*/
        map = mapboxMap;
        locationEnable();
        mapboxMap.getUiSettings().setZoomControlsEnabled(true);
        mapboxMap.getUiSettings().setZoomGesturesEnabled(true);
        mapboxMap.getUiSettings().setScrollGesturesEnabled(true);
        mapboxMap.getUiSettings().setAllGesturesEnabled(true);
    }

    void locationEnable() {
        if (PermissionsManager.areLocationPermissionsGranted(this)) {
            intialLocationEngine();
            intializLocationLayer();
        } else {
            permissionsManager = new PermissionsManager(this);
            permissionsManager.requestLocationPermissions(this);
        }
    }

    void intialLocationEngine() {
        locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
        locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
        locationEngine.activate();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location lastLocation = locationEngine.getLastLocation();
        if (lastLocation != null) {
            originLayout = lastLocation;
            setCamerpostion(lastLocation);
        } else {
            locationEngine.addLocationEngineListener(this);
        }

    }

    void intializLocationLayer() {
        locationLayerPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
        locationLayerPlugin.setLocationLayerEnabled(true);
        locationLayerPlugin.setCameraMode(CameraMode.TRACKING);
        locationLayerPlugin.setRenderMode(RenderMode.NORMAL);
    }

    void setCamerpostion(Location camerpostion) {
        map.animateCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(camerpostion.getLatitude(), camerpostion.getLongitude()), 13.0));
    }

    @Override
    public void onConnected() {
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        locationEngine.requestLocationUpdates();
    }

    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            originLayout = location;
            setCamerpostion(location);
        }
    }

    @Override
    public void onExplanationNeeded(List<String> permissionsToExplain) {

    }

    @Override
    public void onPermissionResult(boolean granted) {
        if (granted) {
            locationEnable();
        }

    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @SuppressWarnings("MissingPermission")
    @Override
    public void onStart() {
        super.onStart();
        if (locationEngine != null)
           locationEngine.requestLocationUpdates();
        mapView.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onStop() {
        super.onStop();
        mapView.onStop();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (locationEngine!=null)
        {
            locationEngine.deactivate();
        }        mapView.onDestroy();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }
}

ここにXmlがあります:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:Android="http://schemas.Android.com/apk/res/Android"
    xmlns:app="http://schemas.Android.com/apk/res-auto"
    xmlns:tools="http://schemas.Android.com/tools"
    Android:layout_width="match_parent"
    Android:layout_height="match_parent"
    tools:context="com.example.joltatech.selfmadmap.Main2Activity">

    <com.mapbox.mapboxsdk.maps.MapView
        Android:id="@+id/mapView"
        Android:layout_width="match_parent"
        Android:layout_height="match_parent"
        app:mapbox_cameraTargetLat="40.73581"
        app:mapbox_cameraTargetLng="-73.99155"
        app:mapbox_styleUrl="@string/mapbox_style_satellite_streets"
        app:mapbox_cameraZoom="11"/>
</RelativeLayout>

Gradleファイルは次のとおりです。

implementation 'com.mapbox.mapboxsdk:mapbox-Android-sdk:6.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-Android-plugin-locationlayer:0.6.0'

そして、プロジェクトレベルでのGradleの使用:

jcenter()
mavenCentral()

mapboxMap.getLocationComponent()。getLastKnownLocation()。getLatitude()

1

ユーザーの最初の場所を取得するには、これが最良のコードであり、私のために働いています

 protected void getLocation() {
    if (isLocationEnabled(MainActivity.this)) {
        locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        criteria = new Criteria();
        bestProvider = String.valueOf(locationManager.getBestProvider(criteria, true)).toString();

        //You can still do this if you like, you might get lucky:
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location location = locationManager.getLastKnownLocation(bestProvider);
        if (location != null) {
            Log.e("TAG", "GPS is on");
            latitude = location.getLatitude();
            longitude = location.getLongitude();
            originLocation=location;
            Toast.makeText(MainActivity.this, "latitude:" + latitude + " longitude:" + longitude, Toast.LENGTH_SHORT).show();
            searchNearestPlace(voice2text);
        }
        else{
            //This is what you need:
            locationManager.requestLocationUpdates(bestProvider, 1000, 0, (Android.location.LocationListener) MainActivity.this);
        }
    }
    else
    {
        //Prompt user to enable location....
        //.................
    }
}
0
Qasim