【问题标题】:Capture Coordinates in Google Map on User Click在用户点击时在谷歌地图中捕获坐标
【发布时间】:2013-10-05 21:51:43
【问题描述】:

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

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

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

在捕捉此类位置方面需要帮助。

【问题讨论】:

    标签: google-maps-api-3


    【解决方案1】:

    你应该在标记上添加点击监听器会给你标记的位置。

    //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
    

    编辑: 你需要这样的东西

    //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
    

    【讨论】:

    • 如果我没记错的话alert(this.position);会提醒[object]
    • 是的,所以我添加了两个单独的变量将帮助您获得单独的 lat、lng。
    • 那么我想你应该删除alert,因为它没有用
    • 这适用于我添加的新标记,但我需要地图上预先存在的位置——中心有一个圆圈和点的位置
    • 表示您想在用户点击地图时在地图上添加圆圈?在当前点击位置。
    【解决方案2】:

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

    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/

    【讨论】:

    • 但是如果用户点击了矩形之外呢?
    【解决方案3】:

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

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

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

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

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

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

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

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

    您可以使用类似于Styled Maps developer's guide 中示例的代码来使用该 JSON(实际上是 JavaScript 对象文字)。有关地图样式的完整列表,另请参阅 MapTypeStyle reference

    【讨论】:

    • 我使用此代码将 poi 标签关闭。不是我想要的最佳解决方案,但现在已经足够了。 var styles = [ { featureType: "poi", elementType: "labels", stylers: [ { visibility: "off" } ] } ]; var styledMap = new google.maps.StyledMapType(styles, {name: "Styled Map"}); map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions); //将样式化地图与MapTypeId相关联并设置为显示。 map.mapTypes.set('map_style', styledMap); map.setMapTypeId('map_style');
    • +1 是的,但是出于各种原因,您可能需要在地图上显示这些图标 - 就像客户说的:图标在哪里?并认为这是一个错误或禁用的地图:)
    【解决方案4】:

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

    Read the google documentation.

    <!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>
    

    【讨论】:

      【解决方案5】:

      如果您将 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()}&amp;lon=${e.latLng.lng()}&amp;APPID=${YOUR_API_KEY}

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-09-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-16
        相关资源
        最近更新 更多