【发布时间】: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()中的<script></script>,渲染clusterMarks的标记?
【问题讨论】:
标签: javascript node.js express google-maps ejs