【问题标题】:GoogleMaps: How to have a polygon and a marker in a single google maps谷歌地图:如何在单个谷歌地图中拥有多边形和标记
【发布时间】:2016-11-08 22:48:03
【问题描述】:

我需要在 Google 地图上组合两种类型的绘图。

1:多边形 - https://developers.google.com/maps/documentation/javascript/examples/polygon-arrays

2:标记 - https://developers.google.com/maps/documentation/javascript/examples/infowindow-simple

我尝试合并代码并进行了各种调整,但它不起作用。它要么显示一个或另一个,要么显示空白页。

甚至可以在一张地图上合并两张图纸吗?有人可以举一个可行的例子吗?

【问题讨论】:

  • 这当然是可能的。你试过什么没用?
  • @geocodezip 我使用相同的地图 id(#map) 但使用不同的函数在地图上绘制要素。对于多边形,我运行 DrawPolygon() 来创建它的多边形坐标,然后调用标记来绘制可用标记列表。这是行不通的。有什么建议吗?
  • edit您的问题添加一个minimal reproducible example,以证明您尝试的方法不起作用(如果您创建两个单独的地图对象,它肯定不会起作用,除非您将它们放入不同<div>)
  • 我不想创建 2 个地图对象,它们位于单个 <div> 上,因为我希望它们加载到单个地图上。
  • 如果您不创建两个地图对象,它应该“工作”。请edit您的问题添加一个 [mvce] 来演示您尝试的方法不起作用(第二个请求)。

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


【解决方案1】:

同一地图上的多边形和标记的简单示例:

<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Polygon+marker example</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 map;

      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          zoom: 5,
          center: {lat: 24.886, lng: -70.268},
          mapTypeId: 'terrain'
        });

        // Define the LatLng coordinates for the polygon.
        var triangleCoords = [
            {lat: 25.774, lng: -80.190},
            {lat: 18.466, lng: -66.118},
            {lat: 32.321, lng: -64.757}
        ];

        // Construct the polygon.
        var bermudaTriangle = new google.maps.Polygon({
          paths: triangleCoords,
          strokeColor: '#FF0000',
          strokeOpacity: 0.8,
          strokeWeight: 3,
          fillColor: '#FF0000',
          fillOpacity: 0.35
        });
        bermudaTriangle.setMap(map);



        // marker
        var uluru = {lat: 21.5012681, lng: -84.0397756};
        var marker = new google.maps.Marker({
          position: uluru,
          map: map,
          title: 'marker title'
        });


      }

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

不要忘记添加您的 google maps API 密钥,而不是 YOUR_API_KEY

【讨论】:

    猜你喜欢
    • 2012-07-01
    • 2013-03-15
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2012-06-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多