【问题标题】:I'm having trouble with Geolocation我在地理定位方面遇到问题
【发布时间】:2016-12-19 17:03:48
【问题描述】:

我试图让这个地理定位脚本工作,但对我自己来说,我总是最终得到“无法检索您的位置”。这是指向具有我想要的实时结果的网页的链接。我已经尝试将 jsfiddle 复制到一个具有所有相同 HTML、JS 和 CSS 的空白文件中。但是我不能让它工作。我是否需要 API 密钥或其他东西。如果您需要我详细说明,我很高兴,谢谢您的时间。

这是直播结果的链接(点击后向下滚动) https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/Using_geolocation

https://jsfiddle.net/yotzincastrejon/bwujL03d/

HTMl
<p><button onclick="geoFindMe()">Show my location</button></p>
<div id="out"></div>

JS
    function geoFindMe() {
  var output = document.getElementById("out");

  if (!navigator.geolocation){
    output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
    return;
  }

  function success(position) {
    var latitude  = position.coords.latitude;
    var longitude = position.coords.longitude;

    output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

    var img = new Image();
    img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

    output.appendChild(img);
  }

  function error() {
    output.innerHTML = "Unable to retrieve your location";
  }

  output.innerHTML = "<p>Locating…</p>";

  navigator.geolocation.getCurrentPosition(success, error);
}

【问题讨论】:

  • 你能分享你自己的代码吗?
  • 问题的标题应该描述您面临的问题,而不是您尝试解决问题时的经验。另外,我们需要查看相关代码。
  • 你用什么浏览器试过?
  • 我已经在 chrome 中尝试过,使用第一个链接中的示例,它工作正常,但是当我复制代码并自己尝试时,没有任何显示。

标签: javascript html


【解决方案1】:

现在工作https://jsfiddle.net/bwujL03d/1/

您需要将此代码放在头部(在页面加载之前)

function geoFindMe() {
var output = document.getElementById("out");

if (!navigator.geolocation){
output.innerHTML = "<p>Geolocation is not supported by your browser</p>";
return;
}

function success(position) {
var latitude  = position.coords.latitude;
var longitude = position.coords.longitude;

output.innerHTML = '<p>Latitude is ' + latitude + '° <br>Longitude is ' + longitude + '°</p>';

var img = new Image();
img.src = "https://maps.googleapis.com/maps/api/staticmap?center=" + latitude + "," + longitude + "&zoom=13&size=300x300&sensor=false";

output.appendChild(img);
}

function error() {
output.innerHTML = "Unable to retrieve your location";
}

output.innerHTML = "<p>Locating…</p>";

navigator.geolocation.getCurrentPosition(success, error);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-23
    • 2021-05-29
    • 2011-05-09
    • 1970-01-01
    • 2021-04-28
    • 2021-01-06
    • 1970-01-01
    • 2021-06-26
    相关资源
    最近更新 更多