epitomz
epitomz

Reputation: 49

Relevant zoom after search in google maps

I just added the search box in my map but after searching for a place (such as countries or cities) the result is not good. The market is set to the center of the place and the zoom is huge.

How can the bounds be defined automatically depending on the size of the place? When the result of the search includes several places, the zoom is good.

Here is my code portion:

var input = (document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);

var searchBox = new google.maps.places.SearchBox((input));

google.maps.event.addListener(searchBox, 'places_changed', function() {
    var places = searchBox.getPlaces();

    for (var i = 0, marker; marker = markers[i]; i++) {
        marker.setMap(null);
    }

    markers = [];
    var bounds = new google.maps.LatLngBounds();
    for (var i = 0, place; place = places[i]; i++) {
        var image = {
            url: place.icon,
            size: new google.maps.Size(71, 71),
            origin: new google.maps.Point(0, 0),
            anchor: new google.maps.Point(17, 34),
            scaledSize: new google.maps.Size(25, 25)
        };

        var marker = new google.maps.Marker({
            map: map,
            icon: image,
            title: place.name,
            position: place.geometry.location
        });

        markers.push(marker);

        bounds.extend(place.geometry.location);
    }

    map.fitBounds(bounds);
});

Thanks for your help!

Upvotes: 4

Views: 4681

Answers (1)

geocodezip
geocodezip

Reputation: 161324

Use google.maps.fitBounds and the geometry.viewport in the place result.

Will only work if there is a single result (or you could use the viewport of the first result).

for (var i = 0, place; place = places[i]; i++) {
    var image = {
        url: place.icon,
        size: new google.maps.Size(71, 71),
        origin: new google.maps.Point(0, 0),
        anchor: new google.maps.Point(17, 34),
        scaledSize: new google.maps.Size(25, 25)
    };

    var marker = new google.maps.Marker({
        map: map,
        icon: image,
        title: place.name,
        position: place.geometry.location
    });

    markers.push(marker);
}

map.fitBounds(places[0].geometry.viewport);

Upvotes: 3

Related Questions