Detecting user location

Open in CodeSandbox

The API lets you get information about the user's probable location by the IP address.

Access to this data is provided by the geolocation static object.

<!DOCTYPE html>
<html>
    <head>
        <title>Examples. Detecting user location</title>
        <meta
            http-equiv="Content-Type"
            content="text/html; charset=UTF-8"
        />
        <!--
        Set your own API-key. Testing key is not valid for other web-sites and services.
        Get your API-key on the Developer Dashboard: https://developer.tech.yandex.ru/keys/
    -->
        <script
            src="https://api-maps.yandex.ru/2.1/?lang=en_RU&amp;apikey=<your API-key>"
            type="text/javascript"
        ></script>
        <script src="geolocation.js" type="text/javascript"></script>
        <style>
            html,
            body,
            #map {
                width: 100%;
                height: 100%;
                padding: 0;
                margin: 0;
            }
        </style>
    </head>
    <body>
        <div id="map"></div>
    </body>
</html>
ymaps.ready(init);

function init() {
    var geolocation = ymaps.geolocation,
        myMap = new ymaps.Map(
            "map",
            {
                center: [55, 34],
                zoom: 10,
            },
            {
                searchControlProvider: "yandex#search",
            }
        );

    /**
     * Comparing the position calculated from the user's IP address
     * and the position detected using the browser.
     */
    geolocation
        .get({
            provider: "yandex",
            mapStateAutoApply: true,
        })
        .then(function (result) {
            // We'll mark the position calculated by IP in red.
            result.geoObjects.options.set(
                "preset",
                "islands#redCircleIcon"
            );
            result.geoObjects.get(0).properties.set({
                balloonContentBody: "My location",
            });
            myMap.geoObjects.add(result.geoObjects);
        });

    geolocation
        .get({
            provider: "browser",
            mapStateAutoApply: true,
        })
        .then(function (result) {
            /**
             * We'll mark the position obtained through the browser in blue.
             * If the browser does not support this functionality, the placemark will not be added to the map.
             */
            result.geoObjects.options.set(
                "preset",
                "islands#blueCircleIcon"
            );
            myMap.geoObjects.add(result.geoObjects);
        });
}