将相同的onClick事件附加到Google地图标记

时间:2017-03-30 08:55:07

标签: javascript google-maps prototype

以下代码来自Google地图教程,对我正在处理的事情进行了一些更改(因此有些部分现在没有意义)。

它有一个onClick事件用于地图,因此如果您点击地图上的随机位置,或者如果您点击特定的“地点”,它将显示路线。

但是,我想将相同的onClick事件附加到标记。这段代码使用了“原型”,我并不太熟悉。

真的,在这一点上,我需要知道的是如何在单击标记时调用ClickEventHandler函数。该功能适用​​于“地点”点击和随机地图点击,但不适用于地图标记的点击。

提前感谢您提供的任何见解。

<!DOCTYPE html >
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <title>Using MySQL and PHP with Google Maps</title>
    <style>
      /* Always set the map height explicitly to define the size of the div
       * element that contains the map. */
      #map {
        height: 100%;
      }
      /* Optional: Makes the sample page fill the window. */
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
    </style>
  </head>

  <body>
    <div id="map"></div>

    <script>
      var customLabel = {
        restaurant: {
          label: 'R'
        },
        bar: {
          label: 'B'
        }
      };

        function initMap() {

        var origin = {lat: -33.871, lng: 151.197};


        var map = new google.maps.Map(document.getElementById('map'), {
          center: origin,
          zoom: 12
        });

        var clickHandler = new ClickEventHandler(map, origin);

        var infoWindow = new google.maps.InfoWindow;

          // Change this depending on the name of your PHP or XML file
          downloadUrl('https://www.tivahost.com/test/maps/NLPOI.php', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('marker');
            Array.prototype.forEach.call(markers, function(markerElem) {
              var name = markerElem.getAttribute('name');
              var address = markerElem.getAttribute('address');
              var type = markerElem.getAttribute('type');
              var point = new google.maps.LatLng(
                  parseFloat(markerElem.getAttribute('lat')),
                  parseFloat(markerElem.getAttribute('lng')));

              var infowincontent = document.createElement('div');
              var strong = document.createElement('strong');
              strong.textContent = name
              infowincontent.appendChild(strong);
              infowincontent.appendChild(document.createElement('br'));

              var text = document.createElement('text');
              text.textContent = address
              infowincontent.appendChild(text);


              var icon = customLabel[type] || {};


            var iconBase = 'https://maps.google.com/mapfiles/kml/shapes/';
            var icons = {
              restaurant: {
                icon: iconBase + 'parking_lot_maps.png'
              },
              bar: {
                icon: iconBase + 'library_maps.png'
              },
              info: {
                icon: iconBase + 'info-i_maps.png'
              }
            };

              var marker = new google.maps.Marker({
                map: map,
                position: point,
                icon: icons[type].icon,

                label: icon.label
              });
              marker.addListener('click', function() {
                infoWindow.setContent(infowincontent);
                infoWindow.open(map, marker);

              });

            });
          });
        }



      /**
       * @constructor
       */
      var ClickEventHandler = function(map, origin) {
        this.origin = origin;
        this.map = map;
        this.directionsService = new google.maps.DirectionsService;
        this.directionsDisplay = new google.maps.DirectionsRenderer;
        this.directionsDisplay.setMap(map);
//        this.placesService = new google.maps.places.PlacesService(map);
        this.infowindow = new google.maps.InfoWindow;
        this.infowindowContent = document.getElementById('infowindow-content');
        this.infowindow.setContent(this.infowindowContent);

        // Listen for clicks on the map.
        this.map.addListener('click', this.handleClick.bind(this));
      };

      ClickEventHandler.prototype.handleClick = function(event) {
        console.log('You clicked on: ' + event.latLng);
        // If the event has a placeId, use it.
        if (event.placeId) {
          console.log('You clicked on place:' + event.placeId);

          // Calling e.stop() on the event prevents the default info window from
          // showing.
          // If you call stop here when there is no placeId you will prevent some
          // other map click event handlers from receiving the event.
          event.stop();
          this.calculateAndDisplayRoutePlace(event.placeId);
//          this.getPlaceInformation(event.placeId);
        }
        else {
          event.stop();
          this.calculateAndDisplayRoute(event.latLng);          
        }
      };

      ClickEventHandler.prototype.calculateAndDisplayRoutePlace = function(placeId) {
        var me = this;
        this.directionsService.route({
          origin: this.origin,
          destination: {placeId: placeId},
          travelMode: 'WALKING'
        }, function(response, status) {
          if (status === 'OK') {
            me.directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      };

      ClickEventHandler.prototype.calculateAndDisplayRoute = function(latLng) {
        var me = this;
        this.directionsService.route({
          origin: this.origin,
          destination: latLng,
          travelMode: 'WALKING'
        }, function(response, status) {
          if (status === 'OK') {
            me.directionsDisplay.setDirections(response);
          } else {
            window.alert('Directions request failed due to ' + status);
          }
        });
      };      

      ClickEventHandler.prototype.getPlaceInformation = function(placeId) {
        var me = this;
        this.placesService.getDetails({placeId: placeId}, function(place, status) {
          if (status === 'OK') {
            me.infowindow.close();
            me.infowindow.setPosition(place.geometry.location);
            me.infowindowContent.children['place-icon'].src = place.icon;
            me.infowindowContent.children['place-name'].textContent = place.name;
            me.infowindowContent.children['place-id'].textContent = place.place_id;
            me.infowindowContent.children['place-address'].textContent =
                place.formatted_address;
            me.infowindow.open(me.map);
          }
        });
      };



      function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
          if (request.readyState == 4) {
            request.onreadystatechange = doNothing;
            callback(request, request.status);
          }
        };

        request.open('GET', url, true);
        request.send(null);
      }

      function doNothing() {}
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAeuBDdFj7e9OS-gIXIKD51gVd3Ko4hod4&callback=initMap">
    </script>
  </body>
</html>

1 个答案:

答案 0 :(得分:0)

我知道这不是一个适当的&#34;回答但是这里有一种方法将click事件绑定到类似情况下的标记,如果你传入place的参数,当你创建一个标记时(即通过搜索回调):

function createPlaceMarker(place) {
    var placeLoc = place.geometry.location;
    var marker = new google.maps.Marker({
        map: map,
        position: place.geometry.location
    });

    google.maps.event.addListener(marker, 'click', function (event) {
        event.placeId = place.place_id;
        clickHandler.handleClick(event);
    });
}

如果你没有标记的place,那么显示该信息窗口是没有意义的。