web-dev-qa-db-fra.com

Android Maps API v2 Changer l'icône MyLocation

J'aimerais remplacer l'icône par défaut utilisée par Android Maps V2 pour "Ma position" (Le petit point/flèche bleu) par ma propre image. J'ai créé ma propre vignette provider qui contient quelques cartes principalement bleues. L'icône par défaut Ma position est donc très difficile à voir. Auparavant, j'aurais simplement annulé la méthode de tirage de la variable MyLocationOverlay, mais il ne semble pas en avoir une dans la nouvelle API. Toute aide est la bienvenue!

EDIT: J'ai également besoin de l'icône pour pouvoir pivoter, de la même manière que la flèche dépend de la façon dont vous faites face. Donc, je ne peux pas simplement utiliser une marker :( normale, il me faut simplement créer une image personnalisée pour cette flèche.

enter image description here

Mise à jour Bonjour à tous, la mise à jour de Google Play autorise désormais les marqueurs à plat et la rotation des marqueurs, ce qui est exactement ce dont j'avais besoin.

22
Gyroscope

La dernière mise à jour des services Google Play vous permet désormais d'utiliser des marqueurs "plats" et de les faire pivoter, ce qui est exactement ce dont j'avais besoin. Voici une version simple de la façon dont je l'ai implémenté. Je peux probablement faire beaucoup pour optimiser et modifier l’animation, mais cela fait le travail pour le moment. Tous les commentaires sont les bienvenus.

Marker mPositionMarker;
GoogleMap mMap;

@Override
public void onLocationChanged(Location location) {

    if (location == null)
        return;

    if (mPositionMarker == null) {

        mPositionMarker = mMap.addMarker(new MarkerOptions()
                .flat(true)
                .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.positionIndicator))
                .anchor(0.5f, 0.5f)
                .position(
                        new LatLng(location.getLatitude(), location
                                .getLongitude())));
    }

    animateMarker(mPositionMarker, location); // Helper method for smooth
                                                // animation

    mMap.animateCamera(CameraUpdateFactory.newLatLng(new LatLng(location
            .getLatitude(), location.getLongitude())));

}

public void animateMarker(final Marker marker, final Location location) {
    final Handler handler = new Handler();
    final long start = SystemClock.uptimeMillis();
    final LatLng startLatLng = marker.getPosition();
    final double startRotation = marker.getRotation();
    final long duration = 500;

    final Interpolator interpolator = new LinearInterpolator();

    handler.post(new Runnable() {
        @Override
        public void run() {
            long elapsed = SystemClock.uptimeMillis() - start;
            float t = interpolator.getInterpolation((float) elapsed
                    / duration);

            double lng = t * location.getLongitude() + (1 - t)
                    * startLatLng.longitude;
            double lat = t * location.getLatitude() + (1 - t)
                    * startLatLng.latitude;

            float rotation = (float) (t * location.getBearing() + (1 - t)
                    * startRotation);

            marker.setPosition(new LatLng(lat, lng));
            marker.setRotation(rotation);

            if (t < 1.0) {
                // Post again 16ms later.
                handler.postDelayed(this, 16);
            }
        }
    });
}
21
Gyroscope

mon moyen simple de solution est de désactiver "ma position" de Google map

et créez ImageView sur la carte avec mon icône puis capturez ImageView avec

onClick et getMyLocation, animateCamera dans onClick

 this.mGoogleMap.getUiSettings().setMyLocationButtonEnabled(false);
 this.mGoogleMap.setMyLocationEnabled(true);

.

@Override
public void onClick(final View v) {

    Location location = this.mGoogleMap.getMyLocation();

        if (location != null) {

            LatLng target = new LatLng(location.getLatitude(), location.getLongitude());
            CameraPosition position = this.mGoogleMap.getCameraPosition();

            Builder builder = new CameraPosition.Builder();
            builder.zoom(15);
            builder.target(target);

            this.mGoogleMap.animateCamera(CameraUpdateFactory.newCameraPosition(builder.build()));

          }    
}
27
Intathep

À partir de la version 3.1.36, vous ne pouvez plus changer l'icône (je pense que cela changera à l'avenir, mais si l'on considère la vitesse de mise en œuvre des améliorations d'API v2, ce ne sera pas avant Noël).

Vous pouvez cependant utiliser un marqueur maintenant, car il a la fonction setIcon.

En gros, vous devez oublier GoogleMap.setMyLocationEnabled, car il apparaîtra toujours au-dessus. Vous allez plutôt créer votre propre LocationClient et utiliser lat, long et reliant à partir de Location pour mettre à jour la Marker. Ajoutez en outre une Circle et utilisez la précision pour obtenir un effet similaire à la visualisation par défaut myLocation.

4
MaciejGórski

Voici le code pour accéder au bouton d'emplacement:

View mv=findViewById(R.id.map);
        View locationButton = ((View) mv.findViewById(Integer.parseInt("1")).getParent()).findViewById(Integer.parseInt("2"));
        RelativeLayout.LayoutParams rlp = (RelativeLayout.LayoutParams) locationButton.getLayoutParams();
// position on right bottom
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, 0);
        rlp.addRule(RelativeLayout.ALIGN_PARENT_TOP, RelativeLayout.TRUE);
        rlp.setMargins(0, 180, 180, 0);
0
user342498

essaye ça; J'utilise ceci pour dessiner un itinéraire sur la carte, mais je mets des icônes pour les marqueurs et pour ma position Déclare ceci pour afficher votre position:

    LocationManager locationManager = (LocationManager) 
    getSystemService(LOCATION_SERVICE);
    Criteria criteria = new Criteria();
    String provider = locationManager.getBestProvider(criteria, true);
    Location myLocation= locationManager.getLastKnownLocation(provider);

    longitude = myLocation.getLongitude();
    latitude  = myLocation.getLatitude();
    fromPosition = new LatLng(latitude, longitude);

Et créer une fonction comme celle que j’avais utilisée pour dessiner sur la carte mais j’ai placé des icônes sur les marqueurs et ma position:

mGoogleMap.clear();
if(response.equalsIgnoreCase("Success"))
{
     ArrayList<LatLng> directionPoint = v2GetRouteDirection.getDirection(document);
     PolylineOptions rectLine = new PolylineOptions().width(7).color(Color.BLUE);

     for (int i = 0; i < directionPoint.size(); i++) {
     rectLine.add(directionPoint.get(i));
     }
     // Adding route on the map
     mGoogleMap.setOnMarkerClickListener(MainActivity.this);
     mGoogleMap.addPolyline(rectLine);
     markerOptions.position(fromPosition);
     markerOptions.draggable(true);
     Marker1 = mGoogleMap.addMarker(new MarkerOptions()
               .position(Estadio)
               .title("Estadio Cuscatlan")
               .snippet("Estadio Cuscatlan")                                                    
               .icon(BitmapDescriptorFactory                                          
               .fromResource(R.drawable.mapmarker))); 
     Marker2 = mGoogleMap.addMarker(new MarkerOptions()
               .position(Metrocentro)
           .title("Metrocentro")
           .snippet("Metrosuelo")
           .icon(BitmapDescriptorFactory
           .fromResource(R.drawable.mapmark
      Marker3 = mGoogleMap.addMarker(new MarkerOptions()
            .position(Mejicanos)
            .title("Mejicanos")
            .snippet("Mejicanos")
            .icon(BitmapDescriptorFactory
            .fromResource(R.drawable.mapmarker)));  
      MarkerMe = mGoogleMap.addMarker(new MarkerOptions()                                             
                        .position(fromPosition) 
                        .icon(BitmapDescriptorFactory
                        .fromResource(R.drawable.car64)));
   }
    Dialog.dismiss();
    } 
} 
0
José De la O