Creating a map with the user's location
This example demonstrates how to create a map that is initially centered on the user's location.
The "get" method of the geolocation function is used for detecting the location. In the parameters, you can set the preferred method of location detection (by IP or using the Geolocation API), the time to wait for a response, and so on. For more information, see the description of the method.
When calling this method, the browser tries to determine the geographical position of the user. If successful, the result is written in the geoObjects map field; otherwise, there is an error message.
In this example, if the location cannot be detected, a map is created with the center in Moscow.
index.html
geolocated_map.js
<!DOCTYPE html>
<html>
<head>
<title>Examples. Creating a map with the user's 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&apikey=<your API-key>"
type="text/javascript"
></script>
<script
src="https://yandex.st/jquery/2.2.3/jquery.min.js"
type="text/javascript"
></script>
<script src="geolocated_map.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(function () {
var map;
ymaps.geolocation.get().then(
function (res) {
var mapContainer = $("#map"),
bounds = res.geoObjects.get(0).properties.get("boundedBy"),
// Calculating the viewport for the user's current location.
mapState = ymaps.util.bounds.getCenterAndZoom(bounds, [
mapContainer.width(),
mapContainer.height(),
]);
createMap(mapState);
},
function (e) {
// If the location cannot be obtained, we just create a map.
createMap({
center: [55.751574, 37.573856],
zoom: 2,
});
}
);
function createMap(state) {
map = new ymaps.Map("map", state);
}
});