【问题标题】:Showing marker in map with ParseGeoPoint使用 ParseGeoPoint 在地图中显示标记
【发布时间】:2019-06-30 20:47:44
【问题描述】:

目前我很难在地图上放置标记。我想做一个应用程序来跟踪我走路时所走的路径。您能帮我提供一个链接来完成此操作吗?如何根据前面的代码将标记放置在地图中?

我按照https://www.back4app.com/docs/android/parse-geopoint 中的解析指南进行操作,但这似乎不起作用。

这是我到目前为止所做的......

package com.example.mac.mycarapp.Fragment;

import android.Manifest;
import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;

import com.example.mac.mycarapp.R;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
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.MarkerOptions;
import com.parse.ParseGeoPoint;
import com.parse.ParseUser;

public class PruebaDeRutaMapsActivity extends FragmentActivity implements OnMapReadyCallback,
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {

    private GoogleMap mMap;
    private GoogleApiClient mGoogleApiClient;
    Location mLastLocation;
    LocationRequest mLocationRequest;
    private static final int REQUEST_LOCATION = 1;
    LocationManager locationManager;

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

        locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);



    }


    /**
     * Manipulates the map once available.
     * This callback is triggered when the map is ready to be used.
     * This is where we can add markers or lines, add listeners or move the camera. In this case,
     * we just add a marker near Sydney, Australia.
     * If Google Play services is not installed on the device, the user will be prompted to install
     * it inside the SupportMapFragment. This method will only be triggered once the user has
     * installed Google Play services and returned to the app.
     */
    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;

        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;
        }

        buildGoogleApiClient();
        mMap.setMyLocationEnabled(true);

        ParseGeoPoint loc=getCurrentUserLocation();

        // Add a marker in Sydney and move the camera
       showCurrentUserInMap(googleMap);

    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient=new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation=location;


        LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        /** Jugar con el valor de ZoomTo para obtener el valor deseado va de 1 a 21*/
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //TODO:Agregar la localizacion a la base de datos

        //https://www.back4app.com/docs/android/parse-geopoint


        if(location != null){
            // if it isn't, save it to Back4App Dashboard

            ParseUser currentUser = ParseUser.getCurrentUser();

            if (currentUser != null) {
                saveCurrentUserLocation();

            } else {
                // do something like coming back to the login activity
            }
        }
        else {
            // if it is null, do something like displaying error and coming back to the menu activity
        }



    }

    /** When the map is connected and the location is being requested*/
    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        /**
         * OJO si esta puesto en high drenara mas rapido la bateria del dispositivo*/
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        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;
        }

        LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

    }

    @Override
    public void onPointerCaptureChanged(boolean hasCapture) {

    }

    private void saveCurrentUserLocation() {
        // requesting permission to get user's location
        if (ActivityCompat.checkSelfPermission(PruebaDeRutaMapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(PruebaDeRutaMapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(PruebaDeRutaMapsActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_LOCATION);
        } else {
            // getting last know user's location
            Location location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);

            // checking if the location is null
            if (location != null) {
                // if it isn't, save it to Back4App Dashboard
                ParseGeoPoint currentUserLocation = new ParseGeoPoint(location.getLatitude(), location.getLongitude());

                ParseUser currentUser = ParseUser.getCurrentUser();

                if (currentUser != null) {
                    currentUser.put("Location", currentUserLocation);
                    currentUser.saveInBackground();
                } else {
                    // do something like coming back to the login activity
                }
            } else {
                // if it is null, do something like displaying error and coming back to the menu activity
            }
        }
    }
        @Override
        public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
        {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults);

            switch (requestCode) {
                case REQUEST_LOCATION:
                    saveCurrentUserLocation();
                    break;
            }
        }
    private ParseGeoPoint getCurrentUserLocation(){

        // finding currentUser
        ParseUser currentUser = ParseUser.getCurrentUser();

        if (currentUser == null) {
            // if it's not possible to find the user, do something like returning to login activity
        }
        // otherwise, return the current user location
        return currentUser.getParseGeoPoint("Location");

    }

    private void showCurrentUserInMap(final GoogleMap googleMap){

        // calling retrieve user's location method of Step 4
        ParseGeoPoint currentUserLocation = getCurrentUserLocation();

        // creating a marker in the map showing the current user location
        LatLng currentUser = new LatLng(currentUserLocation.getLatitude(), currentUserLocation.getLongitude());
        googleMap.addMarker(new MarkerOptions().position(currentUser).title(ParseUser.getCurrentUser().getUsername()).icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_RED)));

        // zoom the map to the currentUserLocation
        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(currentUser, 5));
    }
    }

【问题讨论】:

  • 为什么要使用 ParseGeoPoint,因为您可以使用 LatLng 或 Location 对象获得坐标?
  • 检查这个问题可能对你有帮助:stackoverflow.com/questions/41500765/…
  • 因为我需要每秒跟踪当前位置并追踪我走过的地方

标签: android google-maps parse-server parse-android-sdk


【解决方案1】:

您需要确保每次有新位置时都更新地图。尝试更改此方法:

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation=location;


        LatLng latLng=new LatLng(location.getLatitude(),location.getLongitude());
        mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
        /** Jugar con el valor de ZoomTo para obtener el valor deseado va de 1 a 21*/
        mMap.animateCamera(CameraUpdateFactory.zoomTo(11));

        //TODO:Agregar la localizacion a la base de datos

        //https://www.back4app.com/docs/android/parse-geopoint


        if(location != null){
            // if it isn't, save it to Back4App Dashboard

            ParseUser currentUser = ParseUser.getCurrentUser();

            if (currentUser != null) {
                saveCurrentUserLocation();
                showCurrentUserInMap(mMap);

            } else {
                // do something like coming back to the login activity
            }
        }
        else {
            // if it is null, do something like displaying error and coming back to the menu activity
        }



    }

【讨论】:

  • 你好 davi 我添加了 showCurrentUserInMap(mMap);但还是不行!你还有什么想法吗?也许我错过了别的东西?关于我要开发的步行应用程序,您是否有任何文件我需要在我步行的地图中追踪路线。
  • 能否在showCurrentUserInMap(mMap); 行中添加断点并检查程序是否到达那里?
  • 你好,davi,程序没有到达那里!并且位置标记也没有出现在地图中
  • 至少进入函数了吗?它会在mLastLocation=location; 停止吗?
  • 没有 davi,它甚至没有运行可能是因为我不动?或者它应该运行
猜你喜欢
  • 1970-01-01
  • 2017-10-25
  • 1970-01-01
  • 2018-11-04
  • 2017-01-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多