【问题标题】:How to get Geolocation data and send it from browser to express server如何获取地理位置数据并将其从浏览器发送到快递服务器
【发布时间】:2020-07-12 07:01:04
【问题描述】:

我想获取某个位置的纬度和经度。我正在使用 ejs 文件。 我在 w3shools 上找到了这段代码。但我不知道如何将它包含在 ejs 文件中并将数据返回到服务器。在后端我使用 express。你能帮忙吗?提前谢谢。

var x = document.getElementById("demo");

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

function showPosition(position) {
  x.innerHTML = "Latitude: " + position.coords.latitude + 
  "<br>Longitude: " + position.coords.longitude;
}
<p>Click the button to get your coordinates.</p>
<button onclick="getLocation()">Try It</button>
<p id="demo"></p>

【问题讨论】:

标签: javascript node.js express geolocation ejs


【解决方案1】:

在你的主 nodeJS 文件中,你需要创建一个接收地理位置数据的路由:

const express = require("express");
const { json } = require("body-parser")
const app = express();
app.use(json())
//you probably have the lines above in your code

app.get("/geolocation/:latitude/:longitude", (req, res) => {
    const latitude = req.params.latitude;
    const longitude = req.params.longitude;
    res.status(200).json({"Message": "Coordinates received"})
    //now that you have these in variables on your server, you can process them or store them in your database as you please
})

在前端,在您的 showPosition 函数中,您应该包含一个获取请求,该请求会将纬度和经度发送到您的服务器。要了解有关 fetch 的更多信息,请点击 here

我希望我正确理解了这个问题,这将是有用的

【讨论】:

  • 嘿!感谢您的回复!在 ejs 文件中,由于未定义导航器,我收到错误消息。我该怎么做才能解决这个问题?
  • 恐怕我帮不上忙,对不起
【解决方案2】:

如果你想从 ejs 执行你的代码,那么你需要把它放在 .ejs 文件中的&lt;script&gt; 标签内

<script>
var x = document.getElementById("demo");

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

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

或将所有 JS 代码存储到 ejs 中底部的单独页面和链接

你的文件.js:

(function() {
    var x = document.findElementById('demo');
    ...
)}();

然后在您的 ejs 模板上://在页面底部

<script src="yourFile.js" type="text/javascript"></script>

【讨论】:

    猜你喜欢
    • 2013-10-01
    • 1970-01-01
    • 2015-10-22
    • 1970-01-01
    • 2021-10-22
    • 1970-01-01
    • 1970-01-01
    • 2019-07-20
    • 1970-01-01
    相关资源
    最近更新 更多