Google Map API-结合地理位置和群集标记

时间:2018-10-22 18:07:32

标签: javascript html

我正在创建一个用于广告分类的网站。我希望用户在他们的位置附近的地图上看到该项目的位置。

使用Google的Geolocation和Cluster Markers的JS代码模板分别工作,将它们添加到同一JS后,它们将无法工作。有没有一种方法可以将JS组合在一起以在同一张地图上工作?

预先感谢

编辑-我已经添加了JS代码

/ *地理位置* /

   var map, infoWindow;
  function initMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: {lat: -34.397, lng: 150.644},
      zoom: 6
    });
    infoWindow = new google.maps.InfoWindow;

    // Try HTML5 geolocation.
    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);
  }

/ *地图聚类* /

function initMap(){

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 6,
      center: {lat: 55.378052, lng: -3.435973}
    });

    var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';


    var markers = locations.map(function(location, i) {
      return new google.maps.Marker({
        position: location,
        label: labels[i % labels.length]
      });
    });

    var markerCluster = new MarkerClusterer(map, markers,
        {imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
  }
  var locations = [
    {lat: 55.633792, lng: -4.661550},
    {lat: 55.864239, lng: -4.251806},
    {lat: 55.614302, lng: -4.665554},
    {lat: 55.543781, lng: -4.664010},
    {lat: 55.551993, lng: -4.623667},
    {lat: -26.246920, lng: -4.523914}
  ]

1 个答案:

答案 0 :(得分:0)

在没有任何特定样本的情况下很难回答您的问题。您将需要将地理位置JS代码组合到聚类标记上,这是一个显而易见的答案。因此,如果您有代码示例,我们将为您提供帮助。