【发布时间】:2026-02-04 02:15:02
【问题描述】:
我想在谷歌地图上显示用户的当前位置和国家名称,城市名称我尝试显示未定义的国家和城市名称的代码,如何在谷歌地图上显示国家和城市名称
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDMnYWXbdpKU3t__MXrRMLAMer23E6gRjs"></script>
<script type="text/javascript">
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (p) {
var LatLng = new google.maps.LatLng(p.coords.latitude, p.coords.longitude);
console.log(LatLng);
var mapOptions = {
center: LatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("dvMap"), mapOptions);
console.log(map);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: "<div style = 'height:60px;width:200px'><b>Your location:</b><br />Latitude: " + p.coords.latitude + "<br />Longitude: " + p.coords.longitude+"<br/>Country:"+p.coords.country+"<br/>city:"+p.coords.city
});
google.maps.event.addListener(marker, "click", function (e) {
var infoWindow = new google.maps.InfoWindow();
infoWindow.setContent(marker.title);
infoWindow.open(map, marker);
});
});
} else {
alert('Geo Location feature is not supported in this browser.');
}
</script>
<div id="dvMap" style="width: 500px; height: 500px">
</div>
【问题讨论】:
-
您需要使用一些地理编码 API 对纬度/经度进行地理编码......浏览器不会在对
navigator.geolocation.getCurrentPosition的回调中为您提供该信息 - 要查看浏览器确实为您提供了什么,请阅读the documentation for the [position object 和前面提到的位置对象的坐标属性](developer.mozilla.org/en-US/docs/Web/API/Coordinates) - 没有你可以看到的城市/国家属性 -
您希望代码做什么?使用谷歌记录的地理编码 API 来确定给定纬度/经度的城市/国家?或者,也许您可以阅读谷歌自己的示例代码developers.google.com/maps/documentation/javascript/examples/…
-
console.log(p.coords);输出什么?一个东西。它有country和city键吗?不是。那么你希望p.coords.city怎么输出城市名呢?? -
+ 回答您的“请为我写一些代码” 请求:请表明您已先进行了一些研究。请阅读文档,不要指望别人为你编写代码。
标签: javascript google-maps geolocation