Подтвердить что ты не робот

Как добавить мою кнопку местоположения в Google maps

Я хотел бы знать, можно ли добавить в качестве опции управления по умолчанию опцию мое местоположение.

map with my location button

Есть ли способ сделать это по умолчанию или мне нужно сделать кнопку с геолокацией, а затем запустить событие click на этой кнопке, чтобы перейти к текущему местоположению пользователя?

4b9b3361

Ответ 1

Мы создали такой компонент для Google Maps API v3. Любой пользователь может использовать в пользовательских проектах, чтобы добавить элемент управления, показывающий текущую геолокацию, только с одной строкой кода:

var geoloccontrol = new klokantech.GeolocationControl(map, mapMaxZoom);

после включения в заголовок HTML этого JavaScript:

<script src="https://cdn.klokantech.com/maptilerlayer/v1/index.js"></script>

См:

http://www.maptiler.com/maptilerlayer/

для примера кода и документации.

Show My Location Control on Google Maps API v3

Он добавляет стандартный элемент управления к карте - и один раз постучал - он показывает синий круг вокруг вашего местоположения с размером, полученным из точности доступных данных о местоположении. Если вы не перетащите карту, она будет удерживать вас в позиции после перемещения.

Этот элемент управления разработан для автоматически созданного зрителем http://www.maptiler.com/ - который создает плитки для наложений карт и пользовательских слоев, сделанных из изображений и растровые геоданные.

Примечание: этот ответ является ответом от Показать мое местоположение в Google Maps API версии 3

Ответ 2

Как сказал @Praveen, вы должны сделать это сами. Вот фрагмент кода для добавления кнопки "Ваше местоположение". ссылка на скрипт JS

HTML

<div id="map">Map will be here</div>

CSS

#map {width:100%;height: 400px;}

JS

var map;
var faisalabad = {lat:31.4181, lng:73.0776};

function addYourLocationButton(map, marker) 
{
    var controlDiv = document.createElement('div');

    var firstChild = document.createElement('button');
    firstChild.style.backgroundColor = '#fff';
    firstChild.style.border = 'none';
    firstChild.style.outline = 'none';
    firstChild.style.width = '28px';
    firstChild.style.height = '28px';
    firstChild.style.borderRadius = '2px';
    firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    firstChild.style.cursor = 'pointer';
    firstChild.style.marginRight = '10px';
    firstChild.style.padding = '0px';
    firstChild.title = 'Your Location';
    controlDiv.appendChild(firstChild);

    var secondChild = document.createElement('div');
    secondChild.style.margin = '5px';
    secondChild.style.width = '18px';
    secondChild.style.height = '18px';
    secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
    secondChild.style.backgroundSize = '180px 18px';
    secondChild.style.backgroundPosition = '0px 0px';
    secondChild.style.backgroundRepeat = 'no-repeat';
    secondChild.id = 'you_location_img';
    firstChild.appendChild(secondChild);

    google.maps.event.addListener(map, 'dragend', function() {
        $('#you_location_img').css('background-position', '0px 0px');
    });

    firstChild.addEventListener('click', function() {
        var imgX = '0';
        var animationInterval = setInterval(function(){
            if(imgX == '-18') imgX = '0';
            else imgX = '-18';
            $('#you_location_img').css('background-position', imgX+'px 0px');
        }, 500);
        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                marker.setPosition(latlng);
                map.setCenter(latlng);
                clearInterval(animationInterval);
                $('#you_location_img').css('background-position', '-144px 0px');
            });
        }
        else{
            clearInterval(animationInterval);
            $('#you_location_img').css('background-position', '0px 0px');
        }
    });

    controlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}

function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
        zoom: 15,
        center: faisalabad
    });
    var myMarker = new google.maps.Marker({
        map: map,
        animation: google.maps.Animation.DROP,
        position: faisalabad
    });
    addYourLocationButton(map, myMarker);
}

$(document).ready(function(e) {
    initMap();
}); 

Ответ 3

Карты Google - это индивидуальная реализация их API карт Google. Поэтому вы должны сделать это самостоятельно.

API API API AFIK v3 не предоставляет никакого элемента управления по умолчанию для "показать мое местоположение", однако реализация вашего собственного просто:

  • API v3 предоставляет возможность добавить custom управления к картам, чтобы вы могли легко добавить значок и написать обработчик событий как упомянутых ниже.
  • Используйте "HTML5 Geolocation", который возвращает вам позицию вашего текущего местоположения.
  • Итак, используйте lat/lng и   когда вы нажимаете значок, обработайте его, чтобы поместить marker.

Ответ 4

Я немного поправил скрипт mi3afzal, чтобы отказаться от зависимости jQuery и добавить поддержку сетчатки. Кроме того, я предлагаю использовать событие center_changed, а не dragend, поскольку центр может быть изменен программно, например. при добавлении маркеров и расширений.

https://jsfiddle.net/ogsvzacz/6/.

var map,
    faisalabad = {lat:31.4181, lng:73.0776};

function addYourLocationButton (map, marker) 
{
    var controlDiv = document.createElement('div');

    var firstChild = document.createElement('button');
    firstChild.style.backgroundColor = '#fff';
    firstChild.style.border = 'none';
    firstChild.style.outline = 'none';
    firstChild.style.width = '28px';
    firstChild.style.height = '28px';
    firstChild.style.borderRadius = '2px';
    firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
    firstChild.style.cursor = 'pointer';
    firstChild.style.marginRight = '10px';
    firstChild.style.padding = '0';
    firstChild.title = 'Your Location';
    controlDiv.appendChild(firstChild);

    var secondChild = document.createElement('div');
    secondChild.style.margin = '5px';
    secondChild.style.width = '18px';
    secondChild.style.height = '18px';
    secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-2x.png)';
    secondChild.style.backgroundSize = '180px 18px';
    secondChild.style.backgroundPosition = '0 0';
    secondChild.style.backgroundRepeat = 'no-repeat';
    firstChild.appendChild(secondChild);

    google.maps.event.addListener(map, 'center_changed', function () {
        secondChild.style['background-position'] = '0 0';
    });

    firstChild.addEventListener('click', function () {
        var imgX = 0,
            animationInterval = setInterval(function () {
                imgX = -imgX - 18 ;
                secondChild.style['background-position'] = imgX+'px 0';
            }, 500);

        if(navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(function(position) {
                var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                map.setCenter(latlng);
                clearInterval(animationInterval);
                secondChild.style['background-position'] = '-144px 0';
            });
        } else {
            clearInterval(animationInterval);
            secondChild.style['background-position'] = '0 0';
        }
    });

    controlDiv.index = 1;
    map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}


map = new google.maps.Map(document.getElementById('map'), {
  zoom: 15,
  center: faisalabad
});
var myMarker = new google.maps.Marker({
  map: map,
  animation: google.maps.Animation.DROP,
  position: faisalabad
});
addYourLocationButton(map, myMarker);