I'm doing a project that uses the Maps v2 API. In this map my location appears, which is being updated as soon as I move. I put an icon with the police image, and I wanted this icon to come after me every time I move, or if I'm standing still behind me in the same position. I created a stalK
method that returns a new point based on my location and the location of the police. I tried to implement it, but when I move the cop moves too, but only once.
I leave part of my code essential for this:
public void onMyLocationChange(Location location) {
double latitude = location.getLatitude();
double longitude = location.getLongitude();
lat = String.valueOf(latitude);
longi = String.valueOf(longitude);
posCurrent = new LatLng(latitude, longitude);
posAtuais.add(posCurrent);
posInicial = posAtuais.get(0);
Marker marker = map.addMarker(new MarkerOptions().position(posInicial));
map.moveCamera(CameraUpdateFactory.newLatLngZoom(posCurrent, 19));
PolylineOptions options = new PolylineOptions().width(5).color(mudaLinhaCor(heart_rate)).geodesic(true);
for (int z = 0; z < posAtuais.size(); z++) {
LatLng point = posAtuais.get(z);
options.add(point);
}
line = map.addPolyline(options);
Marker marker1 = map.addMarker(new MarkerOptions().position(POLICE)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.police)));
posAtuaisPolice.add(0, POLICE);
policia = stalk(posCurrent,POLICE, map);
posAtuaisPolice.add(policia);
for(int i = 2; i< posAtuaisPolice.size(); i++){
policia = stalk(posCurrent, posAtuaisPolice.get(i-1), map);
map.addMarker(new MarkerOptions().position(policia)
.icon(BitmapDescriptorFactory.fromResource(R.drawable.police)));
}
}
//A method that computes a new position
public LatLng stalk(LatLng player,LatLng police,GoogleMap mapView){
Projection projection = mapView.getProjection();
Point pointInicial = new Point(); //police
pointInicial = projection.toScreenLocation(police);
Point pointFinal = new Point(); //player
pointFinal = projection.toScreenLocation(player);
double y=0.2;
int x=0;
if((pointInicial.x==pointFinal.x)){
y=pointInicial.y+1;
}else{
double m=(pointFinal.y-pointInicial.y)/(pointFinal.x-pointInicial.x);
double b=pointInicial.y-(m*pointInicial.x);
int i=1;
while(y != (int)y){
if(pointInicial.x<pointFinal.x){
x=pointInicial.x+i;
//System.out.println("entrou no x<xfnal: "+x);
}
else if(pointInicial.x>pointFinal.x){
//System.out.println("entrou no x>xfnal");
x=pointInicial.x-i;
}
y=m*x+b;
//System.out.println("y: : "+y);
i++;
}
}
return projection.fromScreenLocation(new Point(x, (int) y));
}