【问题标题】:How to access an array sent by node/express at server-side and use it at the client-side in google maps?如何在服务器端访问 node/express 发送的数组并在谷歌地图的客户端使用它?
【发布时间】:2021-02-05 10:00:21
【问题描述】:

我试图在谷歌地图上创建我的聚类标记。

客户端

<script>
// from google map docs

function initMap() {

  // array of locations
  const locations = [
    { lat: -31.56391, lng: 147.154312 },
    { lat: -33.718234, lng: 150.363181 },
    { lat: -33.727111, lng: 150.371124 },
    { lat: -33.848588, lng: 151.209834 },
    { lat: -33.851702, lng: 151.216968 },
    { lat: -34.671264, lng: 150.863657 },
    { lat: -35.304724, lng: 148.662905 },
  ];

  // rendering an instance of google maps
  const map = new google.maps.Map(document.getElementById("map"), {
    zoom: 3,
    center: { lat: -28.024, lng: 140.887 },
  });

  // Create an array of alphabetical characters used to label the markers.
  const labels = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

  // Add some markers to the map.
  // Note: The code uses the JavaScript Array.prototype.map() method to
  // create an array of markers based on a given "locations" array.
  // The map() method here has nothing to do with the Google Maps API.
  const markers = locations.map((location, i) => {
    return new google.maps.Marker({
      position: location,
      label: labels[i % labels.length],
    });
  });

  // Add a marker clusterer to manage the markers.
  new MarkerClusterer(map, markers, {
    imagePath: "https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m",
  });
}
</script>

<script src="https://unpkg.com/@google/markerclustererplus@4.0.1/dist/markerclustererplus.min.js">
  // importing marker clusterer required to manage the markers
</script>

<script async defer 
src="https://maps.googleapis.com/maps/api/js?key=<%-process.env.GOOGLE_MAPS_API_KEY%>&callback=initMap">
  // api callback initMap
</script>
  • 正如您在 initMap() 中看到的,有一个名为 locations 的变量,这是一个地理编码格式的位置数组。
  • const markers 正在使用硬编码 locations.map() 并设置标记。

服务器端

app.get("/", async (req, res) => {
  // getting array of places
  const places = await Place.find({});

  // getting an array of marks from places
  // it must be in geocode format:
  // [{ lat: 123, lng: 123 }, { lat: 856, lng: 547 }, { lat: 775, lng: 937 },] ...
  const marks = places
    .filter(function (el) {
      if (el.lat && el.lng) {
        return true;
      }
    })
    .map((el) => ({
      lat: el.lat,
      lng: el.lng,
    }));
  
  // creating a storage for cluster marks
  const clusterMarks = [];

  // spreading the marks array into cluster marks array
  clusterMarks.push(...marks);

  // rendering and passing places and clusterMarks to be used at the client side
  res.render("./index", { places, clusterMarks });
});
  • 如你所料,我想让locations 动态化,所以...
  • 后端正在发送一个名为clusterMarks 的“地理编码格式的位置数组”以供客户端使用。但是,如下面的问题所述,我不知道如何在客户端脚本中访问此变量。
  • 附加信息:使用 Node.js Express 和 EJS。

问题:

  • 如何在客户端访问/带上node/express发送的clusterMarks(数组变量),以便能够在标签内使用它函数initMap()中的&lt;script&gt;&lt;/script&gt;,渲染clusterMarks的标记?

【问题讨论】:

    标签: javascript node.js express google-maps ejs


    【解决方案1】:

    您可以使用JSON.strinigfy/parse 和ejs 的unescaped output tag (&lt;%-) 来执行此操作,请考虑以下简单示例:

    服务器端:

    app.get('/', (req, resp) => {
        const clusterMarks = [{some:"data"}, {another:"object"}];
        resp.render('index', {clusterMarks: JSON.stringify(clusterMarks)})
    })
    

    客户端:

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <script>
            let clusterMarksParsed = JSON.parse('<%- clusterMarks %>');
            for (const mark of clusterMarksParsed) {
                console.log(mark);
            }
        </script>
    </head>
    <body>
    </body>
    </html>
    

    这将打印出来

    {some: "data"}
    {another: "object"}
    

    到浏览器上的控制台。

    【讨论】:

    • 你好@eol,我在let clusterMarksParsed = JSON.parse("[{"lat":7.119495799999999,"lng":34.8450118},{"lat":-2.119495799999999,"lng":-24.8450118}]"); 收到Uncaught SyntaxError: missing ) after argument list 但它似乎快到了......
    • 更新:之前的错误是由于我的更漂亮的配置没有设置为“prettier.singleQuote”:true。现在它正在工作,非常感谢@eol,我试图解决这个问题很长时间了!我现在很开心! :D
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-29
    • 1970-01-01
    • 2017-02-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多