javascript - 如何将 Google 地图信息窗口更改为地理位置标记
问题描述
我遵循了谷歌https://developers.google.com/maps/documentation/javascript/geolocation的教程,这样我就可以在地图上显示用户的位置。它目前看起来像这样,带有一个信息窗口:
但是我想显示一个地理位置标记而不是信息窗口:
这是我的代码:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.520008, 13.404954)
};
infoWindow = new google.maps.InfoWindow;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
有关如何将其从信息窗口更改为地理位置标记的任何帮助都会很棒。提前致谢。
解决方案
要在 Google 地图中使用标记显示位置,您可以尝试以下操作:
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 52.520008, lng: 13.404954},
zoom: 8,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.520008, 13.404954),
map: map,
/*if you want to custom marker icon, you can set icon path here*/
icon: 'your_icon_url',
/* if you don't want to enable dragging, just remove this property */
draggable: true
});
// if you enable dragging, you can initialize this event
// to get latitude, longitude and address
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
var currentLatitude = latLng.lat();
var currentLongitude = latLng.lng();
var geocoder = new google.maps.Geocoder;
var latlng = { lat: currentLatitude, lng: currentLongitude };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
// address
console.log(results);
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
注意:要使用 Google 地图中的地点,您需要libraries=places
在 url 中将 require 作为参数:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places
参考:更多谷歌设计的标记图标,可以参考这里:新的彩色谷歌地图标记的文件名是什么?
推荐阅读
- typescript - NestJs项目中枚举的使用
- python - 用于解析 xml 文件并对 uuid 进行排序的 Python 脚本
- python - 当我尝试在我的 macOS 上编译 skia 时出现跳过“../src”错误 [我试图编译 aseprite]
- vim - 在 Vim 中以编程方式关闭多个缓冲区
- c++ - 快速 C++ 查询 RE 从函数返回字符串
- dotnetnuke - 内置 2sxc 操作缺少图标
- php - 为什么 Recaptcha 不能使用带参数的 url?
- r - R ifelse 多个条件
- perl - 如果 Perl 已经链接到 libm,为什么没有任何功能向用户公开?
- python - 如何从 python 中的测试套件并行运行单元测试?