web-dev-qa-db-fra.com

Google Maps v2 - définir ma position et effectuer un zoom avant

Ma question est la suivante: est-ce que quelqu'un sait comment configurer Google Maps, pour ouvrir à la fois ma position géographique et une vue agrandie?

Actuellement, la vue principale s’ouvre en Afrique, avec un zoom arrière.

Et cela fait maintenant plusieurs jours que je cherche, et je ne trouve que:

1) Vous ne pouvez pas animer deux choses (comme zoomer et aller à ma position) dans une carte Google? Donc, si je peux comprendre comment régler le zoom avant de définir l’animation, alors ce problème sera résolu. Cela a tendance à être le problème, vous pouvez en changer un, mais pas les deux.

2) J'ai trouvé d'autres classes qui pourraient être utiles, mais il n'y a aucune aide pour configurer le code afin que la classe puisse manipuler la carte Google.

C’est le code que j’ai retenu jusqu’à présent, certaines fonctionnent, d’autres pas. Je pensais que certains pourraient être utiles plus tard.

package com.MYWEBSITE.www;

import com.google.Android.gms.maps.CameraUpdateFactory;
import com.google.Android.gms.maps.GoogleMap;
import com.google.Android.gms.maps.SupportMapFragment;
import com.google.Android.gms.maps.model.LatLng;
import Android.content.Context;
import Android.location.Criteria;
import Android.location.Location;
import Android.location.LocationManager;
import Android.os.Bundle;
import Android.support.v4.app.FragmentActivity;
import Android.view.Menu;

public class MainActivity extends FragmentActivity {
private GoogleMap map;  

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main_layout);

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();
    map.setMyLocationEnabled(true);

    //LocationSource a = (LocationSource) getSystemService(Context.LOCATION_SERVICE);
    //LocationManager b = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    //map.setLocationSource(a);

    Criteria criteria = new Criteria();
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    String provider = locationManager.getBestProvider(criteria, false);
    Location location = locationManager.getLastKnownLocation(provider);
    double lat =  location.getLatitude();
    double lng = location.getLongitude();
    LatLng coordinate = new LatLng(lat, lng);

    //CameraPosition.Builder x = CameraPosition.builder();
    //x.target(coordinate);
    //x.zoom(13);

    //Projection proj = map.getProjection();
    //Point focus = proj.toScreenLocation(coordinate);

    //map.animateCamera(CameraUpdateFactory.newLatLng(coordinate));
    map.animateCamera(CameraUpdateFactory.zoomBy(13));
    //map.moveCamera(CameraUpdateFactory.newLatLng(coordinate));


    ////LatLngBounds bounds = mMap.getProjection().getVisibleRegion().latLngBounds;
}
}
122
Dustin

Vous ne pouvez pas animer deux choses (comme zoomer et aller à ma position) sur une carte Google?

Du point de vue du codage, vous les feriez de manière séquentielle:

    CameraUpdate center=
        CameraUpdateFactory.newLatLng(new LatLng(40.76793169992044,
                                                 -73.98180484771729));
    CameraUpdate zoom=CameraUpdateFactory.zoomTo(15);

    map.moveCamera(center);
    map.animateCamera(zoom);

Ici, je déplace d'abord la caméra, puis l'anime, même s'il peut s'agir d'appels animateCamera(). Si GoogleMap les consolide en un seul événement, je ne peux pas le dire, car cela passe trop vite. :-)

Voici l'exemple de projet duquel j'ai extrait le code ci-dessus.


Désolé, cette réponse est imparfaite. Voir réponse de Rob pour un moyen de vraiment faire cela d'un seul coup, en créant un CameraPosition puis en créant un CameraUpdate à partir de ce CameraPosition.

199
CommonsWare

Il est possible de changer d'emplacement, de zoomer, de prendre une orientation et d'incliner d'un coup. Il est également possible de définir la durée sur l'appel animateCamera().

CameraPosition cameraPosition = new CameraPosition.Builder()
    .target(MOUNTAIN_VIEW)      // Sets the center of the map to Mountain View
    .zoom(17)                   // Sets the zoom
    .bearing(90)                // Sets the orientation of the camera to east
    .tilt(30)                   // Sets the tilt of the camera to 30 degrees
    .build();                   // Creates a CameraPosition from the builder
map.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));

Jetez un coup d'œil à la documentation ici:

https://developers.google.com/maps/documentation/Android/views?hl=en-US#moving_the_camera

164
Rob

c'est une solution simple pour votre question

LatLng coordinate = new LatLng(lat, lng);
CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(coordinate, 5);
map.animateCamera(yourLocation);
51
Ali

Essayez de cette façon -

public class SummaryMapActivity extends FragmentActivity implements LocationListener{

 private GoogleMap mMap;
 private LocationManager locationManager;
 private static final long MIN_TIME = 400;
 private static final float MIN_DISTANCE = 1000;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.summary_mapview);

    if (mMap == null) {
        // Try to obtain the map from the SupportMapFragment.
        mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                .getMap();
        // Check if we were successful in obtaining the map.
        if (mMap != null) {
            mMap.addMarker(new MarkerOptions().position(new LatLng(0, 0)).title("Marker"));
        }
    }
    mMap.setMyLocationEnabled(true);

    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, MIN_TIME, MIN_DISTANCE, this); 


}

@Override
public void onLocationChanged(Location location) {
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(latLng, 15);
    mMap.animateCamera(cameraUpdate);
    locationManager.removeUpdates(this);

}

@Override
public void onProviderDisabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String provider) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
    // TODO Auto-generated method stub

}

}

13
Khobaib

Vous pouvez également définir les deux paramètres tels que,

mMap.moveCamera( CameraUpdateFactory.newLatLngZoom(new LatLng(21.000000, -101.400000) ,4) );

Ceci localise votre carte sur une position et un zoom spécifiques. J'utilise ceci pour la mise en place de ma carte.

7
organillero

C'est une réponse tardive mais je pense que cela aidera. Utilisez cette méthode:

protected void zoomMapInitial(LatLng finalPlace, LatLng currenLoc) {
    try {
        int padding = 200; // Space (in px) between bounding box edges and view edges (applied to all four sides of the bounding box)
        LatLngBounds.Builder bc = new LatLngBounds.Builder();

        bc.include(finalPlace);
        bc.include(currenLoc);
        googleMap.moveCamera(CameraUpdateFactory.newLatLngBounds(bc.build(), padding));
    } catch (Exception e) {
        e.printStackTrace();
    }
}

Utilisez cette méthode après avoir chargé la carte. À votre santé!

3
Abx

1.Ajouter le code XML dans votre mise en page pour l'affichage des cartes.

2. Activez google maps api, puis placez-vous ici.

<fragment
                   Android:id="@+id/map"
               Android:name="com.google.Android.gms.maps.MapFragment"
                    Android:layout_width="match_parent"
                    Android:value="ADD-API-KEY"
                    Android:layout_height="250dp"
                    tools:layout="@layout/newmaplayout" />
        <ImageView
            Android:id="@+id/transparent_image"
            Android:layout_width="match_parent"
            Android:layout_height="match_parent"
            Android:src="@color/transparent" />

3.Ajouter ce code dans oncreate.

 MapFragment mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(UpadateProfile.this);

4.Ajouter ce code après oncreate. puis accéder à l'emplacement actuel avec le marqueur placé dans cette

@Override
public void onMapReady(GoogleMap rmap) {
    DO WHATEVER YOU WANT WITH GOOGLEMAP
    map = rmap;
    setUpMap();
}
public void setUpMap() {
    map.setMapType(GoogleMap.MAP_TYPE_HYBRID);
  map.setMyLocationEnabled(true);
    map.setTrafficEnabled(true);
    map.setIndoorEnabled(true);
    map.getCameraPosition();
    map.setBuildingsEnabled(true);
    map.getUiSettings().setZoomControlsEnabled(true);
    markerOptions = new MarkerOptions();
    markerOptions.title("Outlet Location");
    map.setOnMapClickListener(new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick(LatLng point) {
            map.clear();
            markerOptions.position(point);
            map.animateCamera(CameraUpdateFactory.newLatLng(point));
            map.addMarker(markerOptions);
            String all_vals = String.valueOf(point);
            String[] separated = all_vals.split(":");
            String latlng[] = separated[1].split(",");
            MyLat = Double.parseDouble(latlng[0].trim().substring(1));
            MyLong = Double.parseDouble(latlng[1].substring(0,latlng[1].length()-1));
            markerOptions.title("Outlet Location");
            getLocation(MyLat,MyLong);
        }
    });
}
public void getLocation(double lat, double lng) {
    Geocoder geocoder = new Geocoder(UpadateProfile.this, Locale.getDefault());
    try {
        List<Address> addresses = geocoder.getFromLocation(lat, lng, 1);
   } catch (IOException e) {
         TODO Auto-generated catch block
        e.printStackTrace();
        Toast.makeText(this,e.getMessage(),Toast.LENGTH_SHORT).show();
    }
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
1
Venkatesh

Le moyen le plus simple consiste à utiliser CancelableCallback. Vous devriez vérifier que la première action est terminée puis appeler la seconde:

mMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, size.x, height, 0), new CancelableCallback() {

                @Override
                public void onFinish() {
                    CameraUpdate cu_scroll = CameraUpdateFactory.scrollBy(0, 500);
                    mMap.animateCamera(cu_scroll);
                }

                @Override
                public void onCancel() {
                }
            });
1
Yuliya Tarasenko

La réponse de @ CommonsWare ne fonctionne pas vraiment. J'ai trouvé que cela fonctionne correctement:

map.moveCamera(CameraUpdateFactory.newLatLngZoom(new LatLng(-33.88,151.21), 15));
0
iMahdi

Vous ne pouvez pas animer deux choses (comme effectuer un zoom avant et accéder à ma position) sur une même carte Google.
Alors déplacez et animez Camera pour zoomer

googleMapVar.moveCamera(CameraUpdateFactory.newLatLng(LocLtdLgdVar));
googleMapVar.animateCamera(CameraUpdateFactory.zoomTo(10));
0
Sujay U N