Не удается нарисовать многоугольник при изменении местоположения

#java #android #google-maps

#java #Android #google-карты

Вопрос:

Я создаю приложение Google Map для Android на Java. Какая-то «скретч-карта». У меня есть код для рисования многоугольника между точками arraylist, и он также должен добавлять точки LatLng при изменении местоположения. Предполагается, что он принимает LatLng из метода onLocationChanged, но он не работает. К сожалению, код не работает. Пожалуйста, помогите мне!

Мой код:

 

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;

import android.Manifest;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;

import android.content.pm.PackageManager;


import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;

import android.util.Log;

import com.google.android.gms.maps.CameraUpdate;
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;
import com.google.android.gms.maps.model.Polygon;
import com.google.android.gms.maps.model.PolygonOptions;



import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import android.widget.TextView;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    private void alertView() {
        AlertDialog alertDialog = new AlertDialog.Builder(MapsActivity.this).create();
        alertDialog.setTitle("Important!");
        alertDialog.setMessage("To allow our app run properly, please set battery saving mode for our app to 'No limits' in settings");
        alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, "OK",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.dismiss();
                    }
                });
        alertDialog.show();
    }


    private final static int MY_PERMISSIONS_REQUEST = 102;

    private GoogleMap mMap;
    private LatLng mOrigin;
    private LatLng mDestination;
    private BroadcastReceiver broadcastReceiver;
    private TextView textView;
    private LocationListener listener;

    @Override


    @RequiresApi(api = Build.VERSION_CODES.M)

    protected void onCreate(Bundle savedInstanceState) {
        alertView();
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        mOrigin = new LatLng(-27.457, 153.040);
        mDestination = new LatLng(-33.852, 151.211);


        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        final  ArrayList points = new ArrayList();
        points.add(new LatLng(-33.852, 151.211));
        listener = new LocationListener() {
            public void onLocationChanged(Location location) {

                LatLng prev = new LatLng(0, 0);
                int flag = 0;
                LatLng current = new LatLng(location.getLatitude(), location.getLongitude());

                if (flag == 0)  //when the first update comes, we have no previous points,hence this
                {
                    prev = current;
                    flag = 1;
                }
                CameraUpdate update = CameraUpdateFactory.newLatLngZoom(current, 16);
                mMap.addMarker(new MarkerOptions().position(current));
                mMap.animateCamera(update);
                Polygon polygon1 = mMap.addPolygon(new PolygonOptions()
                        .clickable(true)
                        .fillColor(0xffF57F17)
                        .strokeWidth(7)
                        .strokeColor(0xff81C784)
                        .addAll(points));
                prev = current;
                current = null;
            }
// Store a data object with the polygon, used here to indicate an arbitrary type.

        };

    }


    /**
     * This method will manipulate the Google Map on the main screen
     */


    @Override
    public void onMapReady(GoogleMap googleMap) {

        //Google map setup
        mMap = googleMap;
        mMap.getUiSettings().setZoomControlsEnabled(true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(true);

        LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);

        // Show marker on the screen and adjust the zoom level
        mMap.addMarker(new MarkerOptions().position(mOrigin).title("Origin").visible(false));
        mMap.addMarker(new MarkerOptions().position(mDestination).title("Destination").visible(false));

        new TaskDirectionRequest().execute(buildRequestUrl(mOrigin, mDestination));
    }


    /**
     * Create requested url for Direction API to get routes from origin to destination
     */

    private String buildRequestUrl(LatLng origin, LatLng destination) {
        String strOrigin = "origin="   origin.latitude   ","   origin.longitude;
        String strDestination = "destination="   destination.latitude   ","   destination.longitude;
        String sensor = "sensor=false";
        String mode = "mode=driving";

        String param = strOrigin   "amp;"   strDestination   "amp;"   sensor   "amp;"   mode;
        String output = "json";
        String APIKEY = getResources().getString(R.string.google_maps_key);

        String url = "https://maps.googleapis.com/maps/api/directions/"   output   "?"   param   "amp;key="   APIKEY;
        Log.d("TAG", url);
        return url;
    }

    /**
     * Request direction from Google Direction API
     */
    private String requestDirection(String requestedUrl) {
        String responseString = "";
        InputStream inputStream = null;
        HttpURLConnection httpURLConnection = null;
        try {
            URL url = new URL(requestedUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.connect();

            inputStream = httpURLConnection.getInputStream();
            InputStreamReader reader = new InputStreamReader(inputStream);
            BufferedReader bufferedReader = new BufferedReader(reader);

            StringBuffer stringBuffer = new StringBuffer();
            String line = "";
            while ((line = bufferedReader.readLine()) != null) {
                stringBuffer.append(line);
            }
            responseString = stringBuffer.toString();
            bufferedReader.close();
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        httpURLConnection.disconnect();
        return responseString;
    }

    //Get JSON data from Google Direction
    public class TaskDirectionRequest extends AsyncTask<String, Void, String> {
        @Override
        protected String doInBackground(String... strings) {
            String responseString = "";
            try {
                responseString = requestDirection(strings[0]);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return responseString;
        }

        @Override
        protected void onPostExecute(String responseString) {
            super.onPostExecute(responseString);
            //Json object parsing
            TaskParseDirection parseResult = new TaskParseDirection();
            parseResult.execute(responseString);
        }
    }


    //Parse JSON Object from Google Direction API amp; display it on Map
    public class TaskParseDirection extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {
        @Override
        protected List<List<HashMap<String, String>>> doInBackground(String... jsonString) {
            List<List<HashMap<String, String>>> routes = null;
            JSONObject jsonObject = null;

            try {
                jsonObject = new JSONObject(jsonString[0]);
                DirectionParser parser = new DirectionParser();
                routes = parser.parse(jsonObject);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return routes;
        }

        @Override
        protected void onPostExecute(List<List<HashMap<String, String>>> lists) {

            // Add polygons to indicate areas on the map.

            LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            if (ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(MapsActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

                return;
            }
            Location location = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);


        }


        /**
         * Request app permission for API 23/ Android 6.0
         */
        private void requestPermission(String permission) {
            if (ContextCompat.checkSelfPermission(MapsActivity.this, permission) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(MapsActivity.this,
                        new String[]{permission},
                        MY_PERMISSIONS_REQUEST);
            }
        }
    }
}
  

Ответ №1:

Вы реализуете только LocationListener! Вы его не используете

возможно, это может вам помочь

 locationManager.requestLocationUpdates(android.location.LocationManager.GPS_PROVIDER, 5000, 5, locationListener);
  

Комментарии:

1. смотрите этот код github.com/googlemaps/android-samples/blob/master/ApiDemos/java /…