Y
Y
Yuri Voronin2019-11-06 11:02:21
JavaScript
Yuri Voronin, 2019-11-06 11:02:21

How to automatically center the Yandex map (api)?

Hello. You need to add points to the map, combine them into a cluster and center the map depending on the added points.
For centering found:
myMap.setBounds(myMap.geoObjects.getBounds());
My code:

ymaps.ready(init);
    function init(){
        var myMap = new ymaps.Map("map", {
            center: [55.76, 37.64],
            zoom: 7
        });
        var coords = [
            [56.023, 36.988],
            [56.025, 36.981],
            [56.020, 36.981],
            [56.021, 36.983],
            [56.027, 36.987]
        ];
        var myGeoObjects = [];

        for (var i = 0; i<coords.length; i++) {
            myGeoObjects[i] = new ymaps.GeoObject({
                geometry: {
                    type: "Point",
                    coordinates: coords[i]
                },
                properties: {
                    balloonContent: 'Hello World',
                }
            }, {
                preset:'islands#darkGreenDotIcon'
            });
        }

        var myClusterer = new ymaps.Clusterer({
            preset: 'islands#invertedDarkGreenClusterIcons',
        });
        myClusterer.add(myGeoObjects);
        myMap.geoObjects.add(myClusterer);
        myMap.setBounds(myClusterer.getBounds());
    }

Here is the result
63ca892184.png
It seems to be centered, but something like a big zoom is obtained.

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question