按位置JAVASCRIPT验证用户

时间:2018-04-19 10:43:47

标签: javascript html geolocation gps location

我正在尝试开发一个页面,其中有一个可以按下的按钮。按下它时应执行一些功能,但在执行之前,应首先按位置进行验证。因此,每当用户处于默认设置位置(像多边形一样的区域)时,可以按下按钮而不返回错误。当不在该位置或其他错误时,它应该发出警告/错误。

最适合使用哪些插件/库/代码?有什么提示吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您使用的是html5,可以使用navigator.geolocation.getCurrentPosition获取位置。

参考:https://www.w3schools.com/html/html5_geolocation.asp

    <!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <title>Polygon arrays</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>
      // This example requires the Geometry library. Include the libraries=geometry
      // parameter when you first load the API. For example:
      // <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry">

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

        var triangleCoords = [
          {lat: 25.774, lng: -80.19},
          {lat: 18.466, lng: -66.118},
          {lat: 32.321, lng: -64.757}
        ];

        var bermudaTriangle = new google.maps.Polygon({paths: triangleCoords});

        google.maps.event.addListener(map, 'click', function(e) {
          var resultColor =
              google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
              'blue' :
              'red';

          var resultPath =
              google.maps.geometry.poly.containsLocation(e.latLng, bermudaTriangle) ?
              // A triangle.
              "m 0 -1 l 1 2 -2 0 z" :
              google.maps.SymbolPath.CIRCLE;

          new google.maps.Marker({
            position: e.latLng,
            map: map,
            icon: {
              path: resultPath,
              fillColor: resultColor,
              fillOpacity: .2,
              strokeColor: 'white',
              strokeWeight: .5,
              scale: 10
            }
          });
        });
      }
    </script>
    <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=geometry&callback=initMap"
         async defer></script>
  </body>
</html>

获得位置后,您可以使用[Google Maps Geometry Library],对于Polygon,您可以使用:

参考:https://developers.google.com/maps/documentation/javascript/examples/poly-containsLocation

string.IsNullOrEmpty