【问题标题】:separate functions for each map marker click每个地图标记单击的单独功能
【发布时间】:2018-02-07 04:28:42
【问题描述】:

如何为每个地图标记点击调用单独的函数?

对于我的示例,我尝试在单击时滚动到 div,但它总是将我带到最后一个地图标记的 div。当我点击单独的地图标记时如何滚动到单独的 div 或者当有多个地图标记时是否有可能在地图标记点击时触发单独的功能?

正在进行的实验在这里 - http://nayague.com/development/tour/multiple-map-click.html

<!DOCTYPE html>
<html>

<head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    <meta name="robots" content="noindex, nofollow">
    <meta name="googlebot" content="noindex, nofollow">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
    <link rel="stylesheet" type="text/css" href="/css/result-light.css">
    <style type="text/css"></style>
    <title></title>

    <script type='text/javascript'>
        //<![CDATA[
        jQuery(function ($) {
            // Asynchronously Load the map API 
            var script = document.createElement('script');
            script.src =
                "http://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&sensor=false&callback=initialize";
            document.body.appendChild(script);
        });
        function initialize() {
            var map;
            var bounds = new google.maps.LatLngBounds();
            var mapOptions = {
                mapTypeId: 'roadmap'
            };
            // Display a map on the page
            map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
            map.setTilt(45);
            // Multiple Markers
            var markers = [
                ['Anuradhapura', 8.3372688, 80.3619399, '#1'],
                ['Sigiriya', 7.9568242, 80.7434198, '#2'],
                ['Hotel See Kandy', 7.2930541, 80.6159102, '#3']
            ];
            // Display multiple markers on a map
            var infoWindow = new google.maps.InfoWindow(), marker, i;
            // Loop through our array of markers & place each one on the map  
            for (i = 0; i < markers.length; i++) {
                var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
                bounds.extend(position);
                marker = new google.maps.Marker({
                    position: position,
                    map: map,
                    title: markers[i][0],
                    url: markers[i][3]
                });
                google.maps.event.addListener(marker, 'click', function () {
                    console.log('click');
                    // console.log($(marker.url));
                    var elem = $(marker.url);
                    console.log(elem);
                    // alert(elem);

                    $('html, body').animate({
                        scrollTop: elem.offset().top
                    }, 1000);
                });
                // Automatically center the map fitting all markers on the screen
                map.fitBounds(bounds);
            }
            // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
            var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function (event) {
                this.setZoom(8);
                google.maps.event.removeListener(boundsListener);
            });
        }
        //]]>
    </script>

</head>

<body>
    <div id='map_canvas' style="width: 100%;height: 100vh"></div>
    <div class="location-details" id='1'>1</div>
    <div class="location-details" id='2'>2</div>
    <div class="location-details" id='3'>3</div>

    <script>
        // tell the embed parent frame the height of the content
        if (window.parent && window.parent.parent) {
            window.parent.parent.postMessage(["resultsFrame", {
                height: document.body.getBoundingClientRect().height,
                slug: "o8u13whg"
            }], "*")
        }
    </script>

    <script async defer src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"></script>

</body>

<style>
    .location-details {
        background-color: blue;
        color: white;
        width: 100%;
        display: inline-block;
        height: 100vh;
    }
    .location-details:nth-child(odd) {
        background-color: red;
    }
</style>

</html>

【问题讨论】:

  • 你需要了解 javascript 中的闭包...marker 将始终是点击事件处理程序中的最后一个标记,因为那时标记就是这样
  • 嗨,我替换了“var elem = $(marker.url);”通过“var elem = $(this.url);”它奏效了。
  • 您的问题解决了吗?
  • 是的,通过替换“var elem = $(marker.url);” by "var elem = $(this.url); 如上所述 :) 谢谢 :-)

标签: javascript jquery google-maps google-maps-api-3


【解决方案1】:

您需要在 marker 变量上使用函数闭包。 (在问题中解决了类似的问题:Google Maps JS API v3 - Simple Multiple Marker Example 用于 InfoWindows,使用 IIFE)。

// function closure on marker variable for the click event
google.maps.event.addListener(marker, 'click', (function(marker) {
  return function(evt) {
    console.log('click');
    var elem = $(marker.url);
    console.log(elem);

    $('html, body').animate({
      scrollTop: elem.offset().top
    }, 1000);
  }
}(marker)))

proof of concept fiddle

代码 sn-p:

jQuery(function($) {
  // Asynchronously Load the map API 
  var script = document.createElement('script');
  script.src =
    "https://maps.googleapis.com/maps/api/js?callback=initialize";
  document.body.appendChild(script);
});

function initialize() {
  var map;
  var bounds = new google.maps.LatLngBounds();
  var mapOptions = {
    mapTypeId: 'roadmap'
  };
  // Display a map on the page
  map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
  map.setTilt(45);
  // Multiple Markers
  var markers = [
    ['Anuradhapura', 8.3372688, 80.3619399, '#1'],
    ['Sigiriya', 7.9568242, 80.7434198, '#2'],
    ['Hotel See Kandy', 7.2930541, 80.6159102, '#3']
  ];
  // Display multiple markers on a map
  var infoWindow = new google.maps.InfoWindow(),
    marker, i;
  // Loop through our array of markers & place each one on the map  
  for (i = 0; i < markers.length; i++) {
    var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
    bounds.extend(position);
    marker = new google.maps.Marker({
      position: position,
      map: map,
      title: markers[i][0],
      url: markers[i][3]
    });
    // function closure on marker variable for the click event
    google.maps.event.addListener(marker, 'click', (function(marker) {
      return function(evt) {
        var elem = $(marker.url);

        $('html, body').animate({
          scrollTop: elem.offset().top
        }, 1000);
      }
    }(marker)))
    // Automatically center the map fitting all markers on the screen
    map.fitBounds(bounds);
  }
  // Override our map zoom level once our fitBounds function runs (Make sure it only runs once)
  var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
    this.setZoom(8);
    google.maps.event.removeListener(boundsListener);
  });
}
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  padding: 0px;
  margin: 0px;
}

.location-details {
  background-color: blue;
  color: white;
  width: 100%;
  display: inline-block;
  height: 100vh;
}

.location-details:nth-child(odd) {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='map_canvas' style="width: 100%;height: 100vh"></div>
<div class="location-details" id='1'>1</div>
<div class="location-details" id='2'>2</div>
<div class="location-details" id='3'>3</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-11
    • 1970-01-01
    • 2015-07-27
    • 1970-01-01
    相关资源
    最近更新 更多