【问题标题】:Google Maps: Buttons doesn't work to show marker谷歌地图:按钮无法显示标记
【发布时间】:2018-05-01 05:04:41
【问题描述】:

(我对此非常陌生。我正在自学,我知道我的代码很乱。)

我正在使用 Google Maps API,我希望用户单击一个按钮(餐厅 1 或餐厅 2),然后使用上面的标记和 InfoWindow 将地图平移到该餐厅的位置。很简单吧?

到目前为止,这是我的 HTML 代码。

<!DOCTYPE html>
<html>
<title>W3.CSS Template</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="estilo.css">
<link rel="stylesheet" href="fuente1.css">
<link rel="stylesheet" href="fuente2.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">

<!-- Page Container -->
<div class="w3-content w3-margin-top" style="max-width:1400px;">

  <!-- The Grid -->
  <div class="w3-row-padding">
  
    <!-- Left Column -->
<div class="w3-third">
    
      <div class="w3-white w3-text-grey w3-card-4">
        <div class="w3-container">
          <img><br>Choose a restaurant<p><br>
<button id="button" style="width:110px;height:30px;cursor:pointer;">Restaurant 1</button>
<button id="button2" style="width:110px;height:30px;cursor:pointer;">Restaurant 2</button>

            <!-- End Left Column -->    </p>
        </div>
      </div>
</div>

    <!-- Right Column -->
    <div class="w3-twothird">
    
      <div class="w3-container w3-card w3-white w3-margin-bottom">
<h2 class="w3-text-grey w3-padding-16"><i class="fa fa-suitcase fa-fw w3-margin-right w3-xxlarge w3-text-blue"></i>
MAP
</h2><div class="w3-container">
<html>
<body>
<div id="map" style="width:555px;height:500px"></div>
<script>
  function myMap() {
    map = new google.maps.Map(document.getElementById('map'), {
      center: new google.maps.LatLng(31.825948, -116.599869),
      zoom: 16
    });
  }

  function addmarker(lat, lon) {
    marker = new google.maps.Marker({
      position: new google.maps.LatLng(lat, lon),
      map: map
    });
    
    map.panTo(new google.maps.LatLng(lat, lon));
  }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBQ3QnkneaUIsXaJHZtYwqdWxX9KCMj4CA&callback=myMap">"></script>
</body>
</html>
       <br><br>

        </div>
      </div>
<!-- End Right Column -->
    </div>
    
  <!-- End Grid -->
  </div>
  
  <!-- End Page Container -->
</div>
</body>
</html>
</body>
</html>

如您所见,我已经设置好了一切。唯一不起作用的是按钮。

我有以下 Javascript,但我不知道如何在我的 HTML 中实现它。

    $('#button').click(function() {
  addmarker('-22.3157017', '-49.0660877');
});
$('#button2').click(function() {
  addmarker('-23.5936152', '-46.5856465');
});

我很高兴听到任何关于这件事的讲座,任何帮助将不胜感激。

作为参考,我希望它能够像这个一样工作。 Place marker on google maps api with html button

【问题讨论】:

  • 首先你需要修复你的标记

标签: javascript html google-maps google-maps-api-3 google-maps-markers


【解决方案1】:

我没有使用您的标记 - 我创建了自己的标记。

检查您的 javascript 后,一切似乎都正常,除了以下两点:缺少 jQuery按钮事件处理程序的代码放置

您似乎正试图通过按相应的触发器(按钮)将 Google Maps Javascript API Markers 添加到这些位置“-22.3157017,-49.0660877”和“-23.5936152,-46.5856465”。我建议在触发事件后添加标记之前执行 Reverse Geocoding

术语地理编码通常是指翻译人类可读的 地址到地图上的一个位置。做相反的过程, 将地图上的位置翻译成人类可读的地址,是 称为反向地理编码。

您还应该将 jQuery 添加为外部库,以使其事件(例如“.click()”)起作用。你可以下载它here

对于按钮,您应该添加这些行 $('#button1').click(function());和 $('#button1').click(function());在你的 myMap() 函数中。

它应该看起来像这样:

  function myMap() {
    var myLatLng = {lat: 31.825948, lng: -116.599869};

    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });
    $('#button1').click(function(){
      var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
      addMarker( coord, map );
    });
     $('#button2').click(function(){
      var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
      addMarker( coord, map );
    });        
  }

在您的 addMarker 函数中,添加两个接受坐标的参数和地图对象。

function addMarker(params, map) {);

在该函数中,创建一个变量 geocoder,其值为 google.maps.Geocoder() 的新实例。

var geocoder = new google.maps.Geocoder();

有了它,您现在可以使用地理编码方法。 Geocode 方法接受两个参数:位置和回调。在 location 参数中,您需要提供从 addMarker() 函数获取的坐标。

geocoder.geocode({'location' : params}, function( results, status ) {});

回调是我们大部分逻辑的实现部分。回调接受两个参数:结果和状态。如果 statusOK,则 results 参数会返回结果数组。如果是这样,我们现在将遍历每个数组元素,然后创建一个新的 Google Maps Javascript API Markers。在标记上,我们只需为其位置和地图属性提供坐标和地图对象。

if (status === 'OK') {         
  var result = results.map( function( value, index ){
   map.setCenter(params);                                               
   var newMarker = new google.maps.Marker({
       position : params,
       map : map,
    });                 
  });   
 } else {
   alert('Geo not successful: ' + status);
 }

这一行'map.setCenter(params);'设置地图显示的位置。

完整代码如下:

<button id="button1">Restaurant 1</button>
<button id="button2">Restaurant 2</button>
<div id="map"></div>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=myMap">
    </script>

  function myMap() {
    var myLatLng = {lat: 31.825948, lng: -116.599869};
    var map = new google.maps.Map(document.getElementById('map'), {
      zoom: 4,
      center: myLatLng
    });
    $('#button1').click(function(){
      var coord = { lat: parseFloat('-22.3157017'), lng: parseFloat('-49.0660877') };
      addMarker( coord, map );
    });
     $('#button2').click(function(){
      var coord = { lat: parseFloat('-23.5936152'), lng: parseFloat('-46.5856465') };
      addMarker( coord, map );
    });       
  }
  function addMarker(params, map) {

    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({'location' : params}, function( results, status ) {
        if (status === 'OK') {         
            var result = results.map( function( value, index ){
            map.setCenter(params);                                               
            var newMarker = new google.maps.Marker({
              position : params,
              map : map,
              animation: google.maps.Animation.DROP,
            });                 
            });   
          } else {
            alert('Geo not successful: ' + status);
          }

      });

 } 

希望它可以帮助并快乐编码!

【讨论】:

    【解决方案2】:

    我之前已经在 stackoverflow 上回答过如何显示图标和信息窗口的问题,并且刚刚更新了我的 fiddle 以改用 https。以下是您需要注意的非常简单的步骤。

    1. 当您单击该小提琴时,您将看到所有 HTML、JS 和 CSS,我曾用于在地图上显示图标、汽车上的人员列表以及单击它们以在地图上居中的交互性。
    2. 使用 gmap3 库,我在页面上包含了谷歌地图
    3. 使用列表元素,我在每个项目的数据属性中对 &lt;li data-gb="car" data-mapid="sc102" data-isactive="0" data-lat="53.538566" data-long="-0.327017199999951"&gt;Second Car&lt;/li&gt; 的项目位置进行了编码。它可以是餐厅、公园等

    代码中的重要位在 Javascript 中,这些是 事件和 Addmarker 操作以及单击列表项的逻辑。

    { action: 'addMarkers',
    marker:{
    values:ulmarkerspeople,
    options:{
        draggable: false,
        icon:'http://webricate.com/stackoverflow/mapicons/male-2.png'
    },
    events:{
      mouseover: function(marker, event, context){
        var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
        jQuery(listelement).attr('style','background-color:#ccc');
        jQuery(listelement).attr('data-isactive','1');
        var map = $(this).gmap3("get"),
          infowindow = $(this).gmap3({get:{name:"infowindow"}});
        if (infowindow){
          infowindow.open(map, marker);
          infowindow.setContent(context.data.ht);
          jQuery("#customPopup").html(context.data.ht);
            jQuery("#customPopup").show(500);
        } else {
          $(this).gmap3({
            infowindow:{
              anchor:marker, 
              options:{content: context.data.ht}
    
            }
          });
            jQuery("#customPopup").html(context.data.ht);
            jQuery("#customPopup").show(500);
        }
      },
      mouseout: function(marker,event,context){
        var listelement = jQuery("li[data-mapid='"+context.data.id+"']");
        jQuery(listelement).attr('style','background-color:#fff');
        jQuery(listelement).attr('data-isactive','0');
        var infowindow = $(this).gmap3({get:{name:"infowindow"}});
        if (infowindow){
          infowindow.close();
    
          jQuery("#customPopup").hide(500);
          jQuery("#customPopup").html("");
        }
       }
      }
     } 
    }
    

    请通读 fiddle 上的 Javascript cmets,您将了解它的要点。

    【讨论】:

      猜你喜欢
      • 2017-04-20
      • 2017-09-06
      • 2014-10-08
      • 2014-05-17
      • 1970-01-01
      相关资源
      最近更新 更多