1

我正在尝试获取访问者的位置,然后使用地图显示他们的位置。

我尝试将 lat 和 long 值传递给变量 a 和 b,然后使用它来显示地图。

  <p> You are visiting me from:

  <button onclick="getLocation()">Click Here</button>
  </p>
  <p id="geoLoc"></p>

  <script>
    var x = document.getElementById("geoLoc");
    var a = 0;
    var b = 0;

    function getLocation() {
      if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
      } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
      }
    }

    function showPosition(position) {
       a = position.coords.latitude;
        b = position.coords.longitude;
      x.innerHTML = "Latitude: " + a +
        "<br>Longitude: " + b;

    }
    function initMap() {
  // The location of visitor
  var uluru = {lat: a, lng: b};
  // The map, centered at visitor
  var map = new google.maps.Map(
      document.getElementById('map'), {zoom: 4, center: uluru});
  // The marker, positioned at visitor
  var marker = new google.maps.Marker({position: uluru, map: map});
}
  </script>
  <h3> Map of Your Location</h3>
  <div id = "map"></div>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
    </script>
  </div>

预期:在经纬度经过的位置上查看带有标记的地图

实际:没有

4

2 回答 2

1

您需要为包含要显示的地图的 div 定义一个高度,添加style="height: 500px"到属性就可以了。

当您加载页面时,地图也会被初始化,这将在 (0,0) 处显示一个标记。在您收到访问者的地理位置信息后,需要设置标记的位置。地图和标记变量需要在函数范围之外定义,然后您可以在showPosition函数中设置标记。

<p> You are visiting me from:
<button onclick="getLocation()">Click Here</button>
</p>
<p id="geoLoc"></p>

<script>
  var x = document.getElementById("geoLoc");
  var a = 0;
  var b = 0;
  // Map variables with global scope
  var map;
  var marker;

  function getLocation() {
    if (navigator.geolocation) {
      navigator.geolocation.getCurrentPosition(showPosition);
    } else {
      x.innerHTML = "Geolocation is not supported by this browser.";
    }
  }

  function showPosition(position) {
    a = position.coords.latitude;
    b = position.coords.longitude;
    x.innerHTML = "Latitude: " + a +
    "<br>Longitude: " + b;
    // Position of the visitor
    var uluru = {lat: a, lng: b};
    // The marker, positioned at visitor
    marker = new google.maps.Marker({position: uluru, map: map});
    // Center the map on the new marker position
    map.setCenter(marker.getPosition());
  }

  function initMap() {
    // The map, centered to 0,0
    map = new google.maps.Map(
    document.getElementById('map'), {zoom: 4 , center: {lat: 0, lng: 0}});
  }

</script>
<h3> Map of Your Location</h3>
<!-- Set div height for the map -->
<div id = "map" style="height: 500px;"></div>
  <script async defer
  src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
  </script>
</div>
于 2019-05-12T08:39:02.057 回答
0

更一般的答案是GeoLocationDisplay Map。边玩边混——w3schools 是初学者的好去处。

于 2019-05-12T09:05:29.957 回答