45

当用户通过使用以下事件侦听器单击地图时,我正在使用此代码来捕获坐标:

google.maps.event.addListener(map, 'click', function(event) {
    placeMarker(event.latLng);
});

但是,当用户单击地图中已标记的位置时,不会调用此函数。这意味着对于鼠标指针在 Google 地图上变为手形图标的点不调用此函数。

在捕获此类位置时需要帮助。

4

5 回答 5

52

You should add the click listener on marker will give you the position of marker.

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    console.log( latitude + ', ' + longitude );
}); //end addListener

Edit: You need something like this

//Add listener
google.maps.event.addListener(marker, "click", function (event) {
    var latitude = event.latLng.lat();
    var longitude = event.latLng.lng();
    console.log( latitude + ', ' + longitude );

    radius = new google.maps.Circle({map: map,
        radius: 100,
        center: event.latLng,
        fillColor: '#777',
        fillOpacity: 0.1,
        strokeColor: '#AA0000',
        strokeOpacity: 0.8,
        strokeWeight: 2,
        draggable: true,    // Dragable
        editable: true      // Resizable
    });

    // Center of map
    map.panTo(new google.maps.LatLng(latitude,longitude));

}); //end addListener
于 2013-09-30T06:11:10.713 回答
14

另一种解决方案是在地图上放置一个与地图矩形大小相同的多边形,然后收集此矩形的点击次数。

function initialize() {
  var mapDiv = document.getElementById('map-canvas');
  var map = new google.maps.Map(mapDiv, {
    center: new google.maps.LatLng(37.4419, -122.1419),
    zoom: 13,
    mapTypeId: google.maps.MapTypeId.ROADMAP
  });

  google.maps.event.addListener(map, 'bounds_changed', function() {
      var lat1 = 37.41463623043073;
      var lat2 = 37.46915383933881;
      var lng1 = -122.1848153442383;
      var lng2 = -122.09898465576174;  

      var rectangle = new google.maps.Polygon({
         paths : [
           new google.maps.LatLng(lat1, lng1),
           new google.maps.LatLng(lat2, lng1),
           new google.maps.LatLng(lat2, lng2),
           new google.maps.LatLng(lat1, lng2)
         ],
        strokeOpacity: 0,
        fillOpacity : 0,
        map : map
      });
      google.maps.event.addListener(rectangle, 'click', function(args) {  
         console.log('latlng', args.latLng);
    });
  });
}

现在,您还可以获得感兴趣的地方(以及他们喜欢的地方)的 LatLng。

演示-> http://jsfiddle.net/qmhku4dh/

于 2013-09-30T09:57:34.723 回答
4

您说的是 Google 在地图上放置的兴趣点图标。

完全删除这些图标对您有用吗?您可以使用样式化地图来做到这一点。要查看它的外观,请打开样式地图向导并将地图导航到您感兴趣的区域。

单击要素类型的兴趣点,然后单击元素类型下的标签。最后,单击Stylers下的Visibility ,然后单击其下的Off单选按钮。

这应该会删除所有兴趣点图标,而不会影响地图的其余部分样式。随着那些消失,那里的点击将响应您的法线贴图点击事件侦听器。

右侧的地图样式框应显示:

特征类型: poi
元素类型:标签
可见性:关闭

如果结果看起来像您想要的那样,请单击地图样式框底部的显示 JSON 。生成的 JSON 应该是这样的:

[
  {
    "featureType": "poi",
    "elementType": "labels",
    "stylers": [
      { "visibility": "off" }
    ]
  }
]

您可以使用类似于Styled Maps 开发人员指南中示例的代码来使用该 JSON(实际上是 JavaScript 对象文字) 。另请参阅MapTypeStyle 参考以获取地图样式的完整列表。

于 2013-09-30T06:46:51.203 回答
0

如果您将 npm load-google-maps-api 与 webpack 一起使用,这对我有用:

  const loadGoogleMapApi = require("load-google-maps-api");
  loadGoogleMapApi({ key: process.env.GOOGLE_MAP_API_KEY }).then(map => {
    let mapCreated = new map.Map(mapElem, {
      center: { lat: lat, lng: long },
      zoom: 7
    });
    mapCreated.addListener('click', function(e) {
      console.log(e.latLng.lat()); // this gives you access to the latitude value of the click
       console.log(e.latLng.lng()); // gives you access to the latitude value of the click
      var marker = new map.Marker({
        position: e.latLng,
        map: mapCreated
      });
      mapCreated.panTo(e.latLng); // finally this adds red marker to the map on click.

    });
  });

接下来,如果您在应用程序中集成 openweatherMap,您可以使用我在上面的 api 请求中控制台记录的 e.latLng.lat() 和 e.latLng.lng() 的值。这边走:

http://api.openweathermap.org/data/2.5/weather?lat=${e.latLng.lat()}&lon=${e.latLng.lng()}&APPID=${YOUR_API_KEY}

我希望这对某人有所帮助,因为它对我有所帮助。干杯!

于 2020-03-16T20:43:59.500 回答
0

此示例演示在 POI(兴趣点)上使用单击事件侦听器。它侦听 POI 图标上的单击事件,然后使用事件数据中的 placeId 和方向服务.route 请求来计算并显示到单击位置的路线。它还使用 placeId 来获取该地点的更多详细信息。

阅读谷歌文档。

<!DOCTYPE html>
<html>
  <head>
    <title>POI Click Events</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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;
      }
      .title {
        font-weight: bold;
      }
      #infowindow-content {
        display: none;
      }
      #map #infowindow-content {
        display: inline;
      }
    </style>
  </head>
  <body>
    <div id="map"></div>
    <div id="infowindow-content">
      <img id="place-icon" src="" height="16" width="16">
      <span id="place-name"  class="title"></span><br>
      Place ID <span id="place-id"></span><br>
      <span id="place-address"></span>
    </div>
    <script>
      function initMap() {
        var origin = {lat: -33.871, lng: 151.197};

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

      /**
       * @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.calculateAndDisplayRoute(event.placeId);
          this.getPlaceInformation(event.placeId);
        }
      };

      ClickEventHandler.prototype.calculateAndDisplayRoute = 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.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);
          }
        });
      };
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places&callback=initMap"
        async defer></script>
  </body>
</html>
于 2018-08-16T23:58:51.930 回答