gpt4 book ai didi

javascript - 获取访问者的纬度和经度并显示它的谷歌地图

转载 作者:行者123 更新时间:2023-11-28 14:13:56 24 4
gpt4 key购买 nike

我正在尝试获取访问者的位置,然后使用 map 显示他们的位置。

我尝试将纬度和经度值传递给变量 a 和 b,然后使用它们来显示 map 。

  <p> You are visiting me from:

<button onclick="getLocation()">Click Here</button>
</p>
<p id="geoLoc"></p>

<script>
var x = document.getElementById("geoLoc");
var a = 0;
var b = 0;

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
a = position.coords.latitude;
b = position.coords.longitude;
x.innerHTML = "Latitude: " + a +
"<br>Longitude: " + b;

}
function initMap() {
// The location of visitor
var uluru = {lat: a, lng: b};
// The map, centered at visitor
var map = new google.maps.Map(
document.getElementById('map'), {zoom: 4, center: uluru});
// The marker, positioned at visitor
var marker = new google.maps.Marker({position: uluru, map: map});
}
</script>
<h3> Map of Your Location</h3>
<div id = "map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</div>

预期:在经纬度传递的位置上看到带有标记的 map

实际:没有

最佳答案

您需要为包含要显示的 map 的 div 定义一个高度,将 style="height: 500px" 添加到属性中就可以了。

当您加载页面时, map 也会被初始化,这将在 (0,0) 处显示一个标记。收到访客的地理位置信息后,需要设置标记的位置。 map 和标记变量需要在函数范围之外定义,然后您可以在 showPosition 函数中设置标记。

<p> You are visiting me from:
<button onclick="getLocation()">Click Here</button>
</p>
<p id="geoLoc"></p>

<script>
var x = document.getElementById("geoLoc");
var a = 0;
var b = 0;
// Map variables with global scope
var map;
var marker;

function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}

function showPosition(position) {
a = position.coords.latitude;
b = position.coords.longitude;
x.innerHTML = "Latitude: " + a +
"<br>Longitude: " + b;
// Position of the visitor
var uluru = {lat: a, lng: b};
// The marker, positioned at visitor
marker = new google.maps.Marker({position: uluru, map: map});
// Center the map on the new marker position
map.setCenter(marker.getPosition());
}

function initMap() {
// The map, centered to 0,0
map = new google.maps.Map(
document.getElementById('map'), {zoom: 4 , center: {lat: 0, lng: 0}});
}

</script>
<h3> Map of Your Location</h3>
<!-- Set div height for the map -->
<div id = "map" style="height: 500px;"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
</div>

关于javascript - 获取访问者的纬度和经度并显示它的谷歌地图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56097144/

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