我想获取某个位置的纬度和经度。我正在使用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>
答案 0 :(得分:0)
在您的主要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函数中,应包含一个提取请求,该请求将向服务器发送纬度和经度。要查看有关提取的更多信息,请点击here
我希望我理解正确的问题,这对您很有帮助
答案 1 :(得分:0)
如果要从ejs执行代码,则需要将其放在.ejs文件的<script>
标记内
<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底部链接
yourFile.js:
(function() {
var x = document.findElementById('demo');
...
)}();
然后在您的ejs模板上://在页面底部
<script src="yourFile.js" type="text/javascript"></script>