简体   繁体   中英

How do I center new google maps marker

I have this function that adds the new marker to the google maps.

But center does not work. Any advise?

function addMarker(lat, lng, name){
    new google.maps.Marker({
        map: map,
        icon: image,
        position: new google.maps.LatLng(lat, lng),
        title: name,
        center: new google.maps.LatLng(lat, lng),
        zoom: 6
    });
}

But center does not work.

When you create a new marker object via the Google Maps API, you can call the map object's setCenter function, passing in the marker's position:

map.setCenter(marker.position);

That should center the map on the marker.

If you want to animate the process, use panTo instead:

map.panTo(marker.position);

It should also be noted that the center and zoom properties you're attempting to set in the constructor for the Marker object do not exist. Those are properties of the map object itself and need to be set there.

I imagine something like this:

function addMarker(lat, lng, name)
{ 
    var newMarker = new google.maps.Marker({ map: map, 
                                             icon: image, 
                                             position: new google.maps.LatLng(lat, lng), 
                                             title: name });
    map.setCenter(newMarker.position);
    map.setZoom(6);
}

I'd also consider adding map and image to the parameter list of addMarker instead of using "global" scoped objects, or I'd forego using a function at all. That is kind of nit-picky and depends on the need of your code.

More Info Here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM