首页 > 解决方案 > 如何将 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);
      } 

有关如何将其从信息窗口更改为地理位置标记的任何帮助都会很棒。提前致谢。

标签: javascriptgoogle-maps

解决方案


要在 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

参考:更多谷歌设计的标记图标,可以参考这里:新的彩色谷歌地图标记的文件名是什么?


推荐阅读