使用JavaScript获取当前地理位置

问题描述 投票:1回答:1

function showPosition() {
  navigator.geolocation.getCurrentPosition(showMap, error);
}

function showMap(position) {
  // Get location data
  var mylatlong = position.coords.latitude + "," + position.coords.longitude;

  // Set Google map source url
  var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center=" + mylatlong + "&size=50x50";

  // Create and insert Google map
  document.getElementById("embedMap").innerHTML = "<img alt='Map Holder' src='" + mapLink + "'>";
}

function error(err) {
  console.warn(`ERROR(${err.code}): ${err.message}`);
}
<input type="button" value="Add Map" onclick="showPosition()" />

<div id="embedMap">
  <!--Google map will be embedded here-->
</div>

我是Java和HTML的新手,目前正在测试如何获取当前位置并在单击按钮后将其显示在Google地图中。我已经尝试过了,但是仍然无法在地图上获取当前位置。

app.js

function showPosition() {
             navigator.geolocation.getCurrentPosition(showMap);
         }

         function showMap(position) {
             // Get location data
             var latlong = position.coords.latitude + "," + position.coords.longitude;

             // Set Google map source url
             var mapLink = "https://maps.googleapis.com/maps/api/staticmap?center="+latlong+"&zoom=16&size=400x300&output=embed";

             // Create and insert Google map
             document.getElementById("embedMap").innerHTML = "<img alt='Google map' src='"+ mapLink +"'>";
         }

index.html

<input type="button" value="Add Map" onclick="showPosition()"/>
 <div id="embedMap">
        <!--Google map will be embedded here-->
    </div>
javascript html google-maps geolocation
1个回答
0
投票

[如果您想通过在JavaScript和HTML中使用地理位置来获取当前位置,则可能要检查Google Maps API Javascript的sample code。这显示了如何通过使用用户的浏览器的HTML5地理位置功能来创建显示用户或设备在Google地图上地理位置的地图。用户必须同意位置共享,否则将显示错误。阅读有关W3C地理位置标准的更多信息。然后,这会将您的坐标映射到由Maps JavaScript API创建的地图。

这里也是我制作的示例代码的摘录,单击“ Geolocate”按钮后对位置进行了地理定位。请记住使用您自己的API密钥更改字符串YOUR_API_KEY

<!DOCTYPE html>
<html>
  <head>
    <title>Geolocation</title>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
    <meta charset="utf-8">
    <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>
  <button id="myBtn">Geolocate</button>
    <div id="map"></div>
    <script>
      // Note: This example requires that you consent to location sharing when
      // prompted by your browser. If you see the error "The Geolocation service
      // failed.", it means you probably did not give permission for the browser to
      // locate you.
      var map, infoWindow;
      function initMap() {
        map = new google.maps.Map(document.getElementById('map'), {
          center: {lat: -34.397, lng: 150.644},
          zoom: 10
        });
        infoWindow = new google.maps.InfoWindow;
document.getElementById("myBtn").addEventListener("click", function(){
        // Try HTML5 geolocation.
        if (navigator.geolocation) {
          navigator.geolocation.getCurrentPosition(function(position) {
            var pos = {
              lat: position.coords.latitude,
              lng: position.coords.longitude
            };

            infoWindow.setPosition(pos);
            infoWindow.setContent('Location found: ' + pos.lat + ',' + pos.lng);
            infoWindow.open(map);
            map.setCenter(pos);
          }, function() {
            handleLocationError(true, infoWindow, map.getCenter());
          });
        } else {
          // Browser doesn't support Geolocation
          handleLocationError(false, infoWindow, map.getCenter());
        }

    });    
      }

      function handleLocationError(browserHasGeolocation, infoWindow, pos) {
        infoWindow.setPosition(pos);
        infoWindow.setContent(browserHasGeolocation ?
                              'Error: The Geolocation service failed.' :
                              'Error: Your browser doesn\'t support geolocation.');
        infoWindow.open(map);
      }
    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </body>
</html>

希望这会有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.