gpt4 book ai didi

javascript - 如何在 Google map 中添加我的位置按钮?

转载 作者:IT王子 更新时间:2023-10-29 03:16:22 26 4
gpt4 key购买 nike

我想知道是否可以将我的位置按钮添加为默认控件选项。

map with my location button

有什么方法可以将其设置为默认位置,或者我需要制作带有地理位置的按钮,然后触发该按钮上的点击事件,以便将用户导航到当前位置?

最佳答案

正如@Praveen 所说,您必须自己完成。这是一段添加“您的位置”按钮的代码。 JS fiddle link

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();
});

关于javascript - 如何在 Google map 中添加我的位置按钮?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24952593/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com