我正在尝试构建一个基于地图的站点,该站点标识用户的地理位置,在其位置绘制一个标记,然后使用该标记/位置单击数据层(在本例中为GeoJSON层)。本质上,如果用户的位置位于由geojson文件划定的区域上,则该用户的位置应自动触发信息窗口。理想情况下,每次用户更改位置时,都将单击地图以检查此GeoJSON图层以获取信息。

到目前为止,我可以成功获取用户的位置。地图以该位置为中心。而且,在GeoJSON层上的手动单击也可以正确填充信息窗口。但是获取用户位置时,它不会自动单击。

我已经看到了很多示例,其中发生了强制单击标记的情况,但是似乎找不到单击数据层的示例。不幸的是,我更多地是由GIS人员负责此方面的编码工作,这远远超出了我的范围,因此我一直在努力弄清我在哪里出错了。

这是脚本,也许我在这里犯了一个错误:

$<script type="text/javascript">

    //centers the map on Iowa City
        var map,
            currentPositionMarker,
            mapCenter = new google.maps.LatLng(41.661354, -91.534729),
            map;

        function initializeMap()
        {
            map = new google.maps.Map(document.getElementById('map_canvas'), {
               zoom: 18,
               center: mapCenter,
               mapTypeId: google.maps.MapTypeId.ROADMAP
             });

            map.data.loadGeoJson('test2.json');
            map.data.setStyle({
            strokeColor: '#2687bf',
            strokeWeight: 5
            });

             map.data.addListener('click', function(event) {
            document.getElementById('info-box').textContent =
            event.feature.getProperty('description');
        });

        }

        function locError(error) {
            // the current position could not be located
            alert("The current position could not be found!");
        }

        function setCurrentPosition(pos) {
            currentPositionMarker = new google.maps.Marker({
                map: map,
                draggable: true,
                position: new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ),
                title: "Current Position"
            });
            new google.maps.event.trigger( 'test2.json', 'click' );

            map.panTo(new google.maps.LatLng(
                    pos.coords.latitude,
                    pos.coords.longitude
                ));

        }

        function displayAndWatch(position) {
            // set current position
            setCurrentPosition(position);
            // watch position
            watchCurrentPosition();
        }

        function watchCurrentPosition() {
            var positionTimer = navigator.geolocation.watchPosition(
                function (position) {
                    setMarkerPosition(
                        currentPositionMarker,
                        position
                    );
                });
        }

        function setMarkerPosition(marker, position) {
            marker.setPosition(
                new google.maps.LatLng(
                    position.coords.latitude,
                    position.coords.longitude)
            );
        }

        function initLocationProcedure() {
            initializeMap();
            if (navigator.geolocation) {
                navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
            } else {
                alert("Your browser does not support the Geolocation API");
            }
        }

        $(document).ready(function() {
            initLocationProcedure();
        });

    </script>
</head>

<body>
    <div id="map_canvas" style="height:600px;"></div>
     <div id="info-box" style="height:250px;">INFO</div>

</body>

</html>


这是我的JSON和完整HTML文件的链接:
https://sites.google.com/site/ecocritkml/coding

JSON显然特定于爱荷华州的爱荷华市,但可以在文本编辑器中轻松地对其进行修改。任何想法在这里都会很有帮助。

最佳答案

我想我明白了。

我不得不使用一些技巧(有些可能有点脏)


我给setTimeout设置了500ms的延迟;毫无疑问,这本可以做得更优雅
我制作了一个临时多边形,因为它允许使用containsLocation()
我没有点击,但在多边形要素上有一个循环,我在那儿阅读了说明,并将其设置为div


..

<!doctype html>
<html lang="en">
  <head>
      <title>Google maps</title>
      <script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
      <script type="text/javascript" src=http://maps.google.com/maps/api/js?v=3&sensor=true&language=en"></script>
  <style>
      html, body {
        height: 100%;
        margin: 0;
        padding: 0;
      }
      #map_canvas {
        height: 100%;
      }
      #info-box {
        background-color: white;
        border: 1px solid black;
        bottom: 30px;
        height: 20px;
        padding: 10px;
        position: absolute;
        left: 30px;
      }
    </style>

<script type="text/javascript">


    //centers the map on Iowa City
    var map,
        currentPositionMarker,
        mapCenter = new google.maps.LatLng(41.661354, -91.534729),
        map;

    function initializeMap() {
      map = new google.maps.Map(document.getElementById('map_canvas'), {
        zoom: 18,
        center: mapCenter,
        mapTypeId: google.maps.MapTypeId.ROADMAP
      });
      map.data.loadGeoJson('test2.json');
      map.data.setStyle({
        strokeColor: '#2687bf',
        strokeWeight: 5
      });
      map.data.addListener('click', function(event) {
        document.getElementById('info-box').textContent = event.feature.getProperty('description');
      });

    }
    function locError(error) {
        // the current position could not be located
    }
    function setCurrentPosition(pos) {

      currentPositionMarker = new google.maps.Marker({
        map: map,
        draggable: true,
        position: new google.maps.LatLng(
          pos.coords.latitude,
          pos.coords.longitude
        ),
        title: "Current Position"
      });

      // Wait half a second, then take a loop of the features, see if the marker is inside one of them
      setTimeout(function() {
        map.data.forEach(function(feature){
          var figure = feature.getGeometry();
          if(figure.getType() == 'Polygon') {

            // make a temporary polygon, see if the marker is inside
            var tempPolygon = new google.maps.Polygon({
              paths: figure.getAt(0).getArray(),  // @see http://stackoverflow.com/questions/33249127/using-containslocation-with-a-google-maps-data-polygon
              map: null
            });

            if(google.maps.geometry.poly.containsLocation(currentPositionMarker.getPosition(), tempPolygon)) {
              // marker is inside this feature
              // invoke a click. well, just pretend  ...
              document.getElementById('info-box').textContent = feature.getProperty('description');
            }
          }
          var b;
        })
      }, 500);

      map.panTo(new google.maps.LatLng(
        pos.coords.latitude,
        pos.coords.longitude
      ));
    }
    function displayAndWatch(position) {
        // set current position
         setCurrentPosition(position);
        // watch position
        watchCurrentPosition();
    }
    function watchCurrentPosition() {
      var positionTimer = navigator.geolocation.watchPosition(function (position) {
        setMarkerPosition(
          currentPositionMarker,
          position
        );
      });
    }
    function setMarkerPosition(marker, position) {
        marker.setPosition(
          new google.maps.LatLng(
            position.coords.latitude,
            position.coords.longitude
          )
        );
        // now we see if the marker is inside one of the polygons
        var a = 0;
    }
    function initLocationProcedure() {
      initializeMap();
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(displayAndWatch, locError);

      }
      else {
        // alert("Your browser does not support the Geolocation API");
      }
    }
    $(document).ready(function() {
        initLocationProcedure();
    });
    </script>
    </head>
    <body>
        <div id="map_canvas" style="height:600px;"></div>
     <div id="info-box" style="height:250px;">INFO</div>
    </body>
</html>

10-04 22:46
查看更多