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

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

Can't draw a polygon on changing location

问题

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentActivity;
// ...(省略其余导入)

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<LatLng> 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) {
                    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;
            }
        };
    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        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);
        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));
    }

    private String buildRequestUrl(LatLng origin, LatLng destination) {
        // ...(省略)
    }

    private String requestDirection(String requestedUrl) {
        // ...(省略)
    }

    public class TaskDirectionRequest extends AsyncTask<String, Void, String> {
        // ...(省略)
    }

    public class TaskParseDirection extends AsyncTask<String, Void, List<List<HashMap<String, String>>>> {
        // ...(省略)
    }
}
英文:

I'm making a google map android app on java. Some sort of "scratch map".
I have a code to draw a polygon between arraylist points and it should also add LatLng points when location changes. It supposed to take a LatLng from onLocationChanged method but it is not working.
Unfortunatelly code is not working.
Please help me!

My code:


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(&quot;Important!&quot;);
alertDialog.setMessage(&quot;To allow our app run properly, please set battery saving mode for our app to &#39;No limits&#39; in settings&quot;);
alertDialog.setButton(AlertDialog.BUTTON_NEUTRAL, &quot;OK&quot;,
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(&quot;Origin&quot;).visible(false));
mMap.addMarker(new MarkerOptions().position(mDestination).title(&quot;Destination&quot;).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 = &quot;origin=&quot; + origin.latitude + &quot;,&quot; + origin.longitude;
String strDestination = &quot;destination=&quot; + destination.latitude + &quot;,&quot; + destination.longitude;
String sensor = &quot;sensor=false&quot;;
String mode = &quot;mode=driving&quot;;
String param = strOrigin + &quot;&amp;&quot; + strDestination + &quot;&amp;&quot; + sensor + &quot;&amp;&quot; + mode;
String output = &quot;json&quot;;
String APIKEY = getResources().getString(R.string.google_maps_key);
String url = &quot;https://maps.googleapis.com/maps/api/directions/&quot; + output + &quot;?&quot; + param + &quot;&amp;key=&quot; + APIKEY;
Log.d(&quot;TAG&quot;, url);
return url;
}
/**
* Request direction from Google Direction API
*/
private String requestDirection(String requestedUrl) {
String responseString = &quot;&quot;;
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 = &quot;&quot;;
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&lt;String, Void, String&gt; {
@Override
protected String doInBackground(String... strings) {
String responseString = &quot;&quot;;
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&lt;String, Void, List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt;&gt; {
@Override
protected List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; doInBackground(String... jsonString) {
List&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; 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&lt;List&lt;HashMap&lt;String, String&gt;&gt;&gt; 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

得分: 1

你只需要实现LocationListener!不要去使用它。

也许这可以帮助你:

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

You only implement LocationListener! You do not use it

maybe this can help you

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

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

发表评论

匿名网友

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

确定