获取访客的经纬度并显示其谷歌地图

时间:2019-05-12 07:41:39

标签: javascript html css

我试图获取访客的位置,然后使用地图显示他们的位置。

我尝试将经度和经度值传递给变量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>

预期:在通过纬度和经度传递的位置上看到带有标记的地图

实际:没有

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

更一般的答案是GeoLocationDisplay Map。随心所欲-w3schools是初学者的肯定之地。