首页 > 解决方案 > 如何获取地理位置数据并将其从浏览器发送到快递服务器

问题描述

我想获取某个位置的纬度和经度。我正在使用 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>

标签: javascriptnode.jsexpressgeolocationejs

解决方案


在您的主 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 的更多信息,请单击此处

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


推荐阅读