简体   繁体   中英

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.
  • The const markers is using the hard-coded locations to .map() over and set the markers.

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...
  • The backend is sending an "array of locations in geocode format" called clusterMarks to be used at the client-side. 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.

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 ?

You can use JSON.strinigfy/parse and ejs's unescaped output tag ( <%- ) to do this, consider this simple example:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM