【问题标题】:Google Maps API: Want geolocation to click automatically on data layer belowGoogle Maps API:希望地理位置自动点击下面的数据层
【发布时间】:2015-11-23 22:55:14
【问题描述】:

我正在尝试构建一个基于地图的站点,该站点可识别用户的地理位置,在他/她的位置绘制一个标记,然后使用该标记/位置单击数据层(在本例中为 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 显然是爱荷华州爱荷华市特有的,但它可以在文本编辑器中轻松修改。任何想法在这里都会很有帮助。

【问题讨论】:

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


    【解决方案1】:

    我想我明白了。

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

    • 我使用 setTimeout 设置了 500 毫秒的延迟;毫无疑问,这本可以更优雅地完成

    • 我制作了一个临时多边形,因为它允许使用 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>
    

    【讨论】:

    • 是的。太感谢了!这似乎工作得很好。我在手机上进行了现场测试,虽然有时会受到一些影响,但我认为这不是代码的问题。只是它工作正常这一事实对我来说就足够了。嘿,不管脏不脏,这对我有很大帮助。非常感谢您的宝贵时间。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多