英文:
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("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
你只需要实现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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论