Documentation
Reference
2.1.50 (current version)
collection
interactivityModel
Interfaces

Detecting the user's location

The API includes a feature for detection the user's location (geolocation). The static geolocation object is used for working with geolocation. There are three modes available for detecting user location:

  • By the IP address according to Yandex data (this method is usually accurate to the city or region).
  • Using the Geolocation API (this method is more accurate on mobile devices, but the user must allow the web page to get location information).
  • Calling both methods and selecting the more accurate result.

The geolocation method is selected by specifying the 'provider' option - the methods listed correspond to the values 'yandex', 'browser', and 'auto', respectively. By default, the 'auto' method is used.

Geolocation results will be returned in the same format as the results of geocoding — a collection of geo objects with a single placemark corresponding to the user's location. By default, the user's coordinates are automatically reverse geocoded, i.e. the user's address, city, and region are determined automatically (this behavior can be disabled by setting the option 'autoReverseGeocode' to false).

// Example of detecting the user's region
// and creating a map that shows this region
ymaps.geolocation.get().then(function (res) {
        // Assumes that jQuery is enabled on the page
    var $container = $('YMapsID'),
        bounds = res.geoObjects.get(0).properties.get('boundedBy'),
        mapState = ymaps.util.bounds.getCenterAndZoom(
            bounds,
            [$container.width(), $container.height()]
        ),
        map = new ymaps.Map('YMapsID', mapState);
}, function (e) {
    console.log(e);
});