javascript - 如何获取地理位置数据并将其从浏览器发送到快递服务器
问题描述
我想获取某个位置的纬度和经度。我正在使用 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>
解决方案
在您的主 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 的更多信息,请单击此处
我希望我正确理解了这个问题,这将很有用
推荐阅读
- bash - 检查bash中的下一行
- angular - 使用生成的客户端代码无法上传文件
- pandas - agg 函数在 pandas 数据框中返回错误的结果
- c - C中具有不同类型的外部变量
- pine-script - 如何在此脚本中插入 heikinashi 过滤器?
- r - `pkgdown` 网站中的`README` 徽章未正确呈现
- javascript - 当我保存到我的数据库时,我没有收到我的数据
- android - 致命异常:OkHttp Dispatcher 出现在 OkHttp 拦截器中,用于更新 OAuth 令牌
- python - 使用 shlex.split 将其中包含多个 " 的字符串作为一个字符串
- django - Manage.py migrate 在第 14 步“提供数据库”的 Heroku python“入门指南”中失败