我正在开发一个获取当前用户位置并在该位置添加标记的应用。还有三个具有静态位置的标记,还有一个称为“ drawCircle”的函数,该函数在这些标记周围绘制圆圈以测量这三个标记位置与用户当前位置之间的距离。
“头像”类包含一个构造函数,该构造函数由三个标记名称(经度和纬度)组成。
我如何随机设置三个标记位置,以便它们随时间变化?
这是我的代码:
public class MapsActivity extends FragmentActivity implements
OnMapReadyCallback,
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
LocationListener{
private GoogleMap mMap;
private GoogleMap firstMarker;
private GoogleMap secondMarker;
private GoogleMap thirdMarker;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private Location mlocation;
private LocationManager locationManager;
private Marker currentUserLocationMarker;
Avatar[] character;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_maps);
googleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// 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);
Avatar = new Avatar[3];
Avatar[0] = new Avatar("firstMarker", 1000, 1000, 45.827159, 13.341452);
Avatar[1] = new Avatar("secondMarker", 1000, 1000, 45.886060, 13.284799);
Avatar[2] = new Avatar("thirdMarker", 1000, 1000, 45.825058, 13.345014);
}
@Override
public void onMapReady(GoogleMap googleMap) {
mMap = googleMap;
firstMarker = googleMap;
secondMarker = googleMap;
thirdMarker = googleMap;
LatLng posFirstMarker = new LatLng(Avatar[0].Lat, Avatar[0].Long);
LatLng posSecondMarker = new LatLng(Avatar[1].Lat, Avatar[1].Long);
LatLng posThirdMarker = new LatLng(Avatar[2].Lat, Avatar[2].Long);
BitmapDrawable dr = (BitmapDrawable) getResources().getDrawable(R.drawable.firstMarkerImg);
Bitmap bitmapD = Bitmap.createScaledBitmap(dr.getBitmap(), 200, 200, false);
BitmapDrawable bt = (BitmapDrawable) getResources().getDrawable(R.drawable.secondMarkerImg);
Bitmap bitmapB = Bitmap.createScaledBitmap(bt.getBitmap(), 200, 200, false);
BitmapDrawable sp = (BitmapDrawable) getResources().getDrawable(R.drawable.thirdMarkerImg);
Bitmap bitmapS = Bitmap.createScaledBitmap(sp.getBitmap(), 125, 125, false);
firstMarker.addMarker(new MarkerOptions().snippet("My Snippet").icon(BitmapDescriptorFactory.fromBitmap(bitmapB)).position(posFirstMarker).title("Pipistrello"));
firstMarker.moveCamera(CameraUpdateFactory.newLatLng(posFirstMarker));
secondMarker.addMarker(new MarkerOptions().snippet("My Snippet").icon(BitmapDescriptorFactory.fromBitmap(bitmapD)).position(posSecondMarker).title("Drago"));
secondMarker.moveCamera(CameraUpdateFactory.newLatLng(posSecondMarker));
thirdMarker.addMarker(new MarkerOptions().snippet("My Snippet").icon(BitmapDescriptorFactory.fromBitmap(bitmapS)).position(posThirdMarker).title("Serpe"));
thirdMarker.moveCamera(CameraUpdateFactory.newLatLng(posThirdMarker));
private GoogleMap Mymarker;
@Override
public void onMapReady (GoogleMap googleMap){
Mymarker = googleMap;
LatLng markerPosition = new LatLng(Lat, Long);
BitmapDrawable dr = (BitmapDrawable) getResources().getDrawable(R.drawable.my_image);
Bitmap bitmapD = Bitmap.createScaledBitmap(dr.getBitmap(), 200, 200, false);
Mymarker.addMarker(new MarkerOptions().snippet("My Snippet").icon(BitmapDescriptorFactory.fromBitmap(bitmapD)).position(markerPosition).title("Marker"));
Mymarker.moveCamera(CameraUpdateFactory.newLatLng(markerPosition));
}
}
@Override
public void onConnected(Bundle bundle) {
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;
}
startLocationUpdates();
mlocation = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);
if (mlocation == null) {
startLocationUpdates();
}
if (mlocation != null) {
double latitude = mlocation.getLatitude();
double longitude = mlocation.getLongitude();
} else {
Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
protected void startLocationUpdates() {
// Create the location request
locationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(1100)
.setFastestInterval(1100);
// Request location updates
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(googleApiClient,
locationRequest, this);
Log.d("reque", "--->>>>");
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
@Override
public void onStart() {
super.onStart();
googleApiClient.connect();
}
@Override
public void onStop() {
super.onStop();
if (googleApiClient.isConnected()) {
googleApiClient.disconnect();
}
}
@Override
public void onLocationChanged(Location location) {
mlocation = location;
if (currentUserLocationMarker != null) {
currentUserLocationMarker.remove();
}
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Location");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_ORANGE));
currentUserLocationMarker = mMap.addMarker(markerOptions);
drawCircle(new LatLng(location.getLatitude(), location.getLongitude()));
Distance(new LatLng(location.getLatitude(), location.getLongitude()));
mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
//mMap.animateCamera(CameraUpdateFactory.zoomBy(13));
if (googleApiClient != null) {
LocationServices.FusedLocationApi.removeLocationUpdates(googleApiClient, this);
}
}
private void drawCircle(LatLng point) {
// Instantiating CircleOptions to draw a circle around the marker
CircleOptions circleOptions = new CircleOptions();
// Specifying the center of the circle
circleOptions.center(point);
// Radius of the circle
circleOptions.radius(1000);
// Border color of the circle
circleOptions.strokeColor(Color.BLACK);
// Fill color of the circle
circleOptions.fillColor(0x30ff0000);
// Border width of the circle
circleOptions.strokeWidth(2);
// Adding the circle to the GoogleMap
mMap.addCircle(circleOptions);
}
private void Distance(LatLng distance) {
float[] results = new float[1];
for (int i = 0; i < 3; i++) {
Location.distanceBetween(mlocation.getLatitude(), mlocation.getLongitude(),
Avatar[i].Lat, Avatar[i].Long, results);
}
}}
答案 0 :(得分:2)
我在我的应用程序中执行了类似的操作,以防止标记相互重叠。每当加载它们时,我都会添加一个小的随机偏移量(这是一种简单且非常有效的技巧)。因此,从技术上讲,每次加载标记时,标记处于不同的位置。您可能可以修改我的代码以实现所需的内容。
我从db(字符串)获取坐标,将其解析为两倍,并添加一个小的随机偏移量。您可以根据需要增加偏移量。
new LatLng(parseCoordRandom(arrayList.get(i).getLatitude()), parseCoordRandom(arrayList.get(i).getLongitude()))
public static double parseCoordRandom(@NonNull String s_coord)
return tryParseStringToDouble(s_coord, 0.0) +getMarkerOffset();
}
public static double tryParseStringToDouble(@NonNull String s, double defaultValue) {
try {
return Double.parseDouble(s);
} catch (NumberFormatException e) {
return defaultValue;
}
}
public static double getMarkerOffset(){
//add tiny random offset to keep markers from dropping on top of themselves
double offset =Math.random()/4000;
boolean isEven = ((int)(offset *400000)) %2 ==0;
if (isEven) return offset;
else return -offset;
}