有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java无法在更改位置时绘制多边形

我正在java上制作一个谷歌地图安卓应用程序。某种“草稿图”。 我有一个在arraylist点之间绘制多边形的代码,它还应该在位置更改时添加LatLng点。它应该从onLocationChanged方法中获取一个LatLng,但它不起作用。 不幸的是,代码不起作用。 请帮帮我

我的代码:



import 安卓x.annotation.RequiresApi;
import 安卓x.appcompat.app.AlertDialog;
import 安卓x.core.app.ActivityCompat;
import 安卓x.core.content.ContextCompat;
import 安卓x.fragment.app.FragmentActivity;

import 安卓.Manifest;

import 安卓.content.BroadcastReceiver;
import 安卓.content.Context;
import 安卓.content.DialogInterface;

import 安卓.content.pm.PackageManager;


import 安卓.location.Location;
import 安卓.location.LocationListener;
import 安卓.location.LocationManager;
import 安卓.os.AsyncTask;
import 安卓.os.Build;
import 安卓.os.Bundle;

import 安卓.util.Log;

import com.google.安卓.gms.maps.CameraUpdate;
import com.google.安卓.gms.maps.CameraUpdateFactory;
import com.google.安卓.gms.maps.GoogleMap;
import com.google.安卓.gms.maps.OnMapReadyCallback;
import com.google.安卓.gms.maps.SupportMapFragment;
import com.google.安卓.gms.maps.model.LatLng;
import com.google.安卓.gms.maps.model.MarkerOptions;
import com.google.安卓.gms.maps.model.Polygon;
import com.google.安卓.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 安卓.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 && 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 + "&" + strDestination + "&" + sensor + "&" + mode;
        String output = "json";
        String APIKEY = getResources().getString(R.string.google_maps_key);

        String url = "https://maps.googleapis.com/maps/api/directions/" + output + "?" + param + "&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 & 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 && 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) 个答案

  1. # 1 楼答案

    您只实现LocationListener!你不用它

    也许这能帮到你

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