简体   繁体   English

如何在服务器端访问 node/express 发送的数组并在谷歌地图的客户端使用它?

[英]How to access an array sent by node/express at server-side and use it at the client-side in google maps?

I was trying to create my clustering markers over the google maps.我试图在谷歌地图上创建我的聚类标记。

client side客户端

<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>
  • As you can see inside the initMap() , there is a variable called locations and this is an array of locations in geocode format.正如您在initMap()中看到的,有一个名为locations的变量,这是一个地理编码格式的位置数组。
  • The const markers is using the hard-coded locations to .map() over and set the markers. const markers使用硬编码的locations.map()覆盖并设置标记。

server side服务器端

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 });
});
  • As you supposed, I want to make the locations dynamic, so...如你所料,我想让locations动态化,所以...
  • The backend is sending an "array of locations in geocode format" called clusterMarks to be used at the client-side.后端正在发送一个名为clusterMarks的“地理编码格式的位置数组”,以在客户端使用。 But, as described in the question below, I don't know how a way to access this variable at the client-side script.但是,如下面的问题所述,我不知道如何在客户端脚本中访问此变量。
  • Additional info: Using Node.js Express and EJS.附加信息:使用 Node.js Express 和 EJS。

Question:问题:

  • How to access/bring the clusterMarks (array variable) sent by node/express at the client-side , to be able to use it inside the tag <script></script> in the function initMap() , to render the marks of clusterMarks ?如何在客户端访问/携带 node/express 发送的clusterMarks (数组变量) ,以便能够在 function initMap()中的标签<script></script>内使用它,以呈现标记clusterMarks

You can use JSON.strinigfy/parse and ejs's unescaped output tag ( <%- ) to do this, consider this simple example:您可以使用JSON.strinigfy/parse和 ejs 的未转义 output 标记<%- )来执行此操作,请考虑以下简单示例:

Server-side:服务器端:

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

Client-side:客户端:

<!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>

This will print这将打印

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

to the console on the browser.到浏览器上的控制台。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在Angular / Node.js / Express中将客户端参数传递给服务器端 - How to pass client-side parameters to the server-side in Angular/Node.js/Express 如何在node / express和Backbone中混合混合(服务器端和客户端渲染)? - How to mix hybrid (server-side and client-side rendering) in node/express and Backbone? 从服务器端获取客户端变量(express.js,node.js) - Get variable on client-side from the server-side (express.js, node.js) 使用 express 和 mongoose,如何使用 POST 路由将多个 ID 的数组从客户端发送到服务器端? - Using express and mongoose, how do I send an array of multiple IDs from the client-side to server-side using a POST route? 节点中的常见服务器端和客户端api调用 - Common server-side and client-side api calls in node 导出服务器端功能以供客户端使用 - Export server-side function for client-side use 从node.js(服务器端)获取数组以响应app.js(客户端) - Get array from node.js (server-side)to react app.js (client-side) 客户端或服务器端处理? - Client-side or server-side processing? 服务器端和客户端JavaScript - Server-side and client-side JavaScript 客户端还是服务器端框架? - Client-side or server-side framework?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM