我有一个对Google Directions API的API调用,然后我 正在尝试通过此代码将JSON响应保存到名为lat的变量中
app.post("/from", function(req,res) {
from = req.body.from;
to = req.body.to;
const url = "https://maps.googleapis.com/maps/api/directions/json?origin="+ from + "&destination=" + to + "&key=AIzaSyDYRICW4Bm4donS0-9LCp_h0nlsyWvEuGY";
console.log(from,to);
https.get(url, function(response) {
console.log(response.statusCode);
var buffers = []
response
.on('data', function(data) {
buffers.push(data)
})
.on('end', function() {
lat = JSON.parse(Buffer.concat(buffers).toString());
console.log(lat);
现在,在我的ejs文件中,我想将此响应传递到script标签中以呈现地图。
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 12
});
var routes = directionsServiceResponse.routes;
console.log("legs " + routes[0].legs.length);
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < routes[0].legs.length; i++) {
var leg = routes[0].legs[i];
for (var j = 0; j < leg.steps.length; j++) {
var step = leg.steps[j];
var color = "black";
if (step.travel_mode == "WALKING")
color = "red";
else if (step.travel_mode == "TRANSIT")
color = "green";
var polyline = new google.maps.Polyline({
path: google.maps.geometry.encoding.decodePath(step.polyline.points),
map: map,
strokeColor: color
});
google.maps.event.addListener(polyline, 'click', function(evt) {
infowindow.setContent("leg " + i + " polyline " + j)
})
for (var ii = 0; ii < polyline.getPath().getLength(); ii++) {
bounds.extend(polyline.getPath().getAt(ii));
}
}
}
map.fitBounds(bounds);
}
var directionsServiceResponse = <%= var %>
</script>
<div id="map"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script src="https://maps.googleapis.com/maps/api/js?key=key&callback=initMap&libraries=geometry" async defer></script>
我尝试过将该变量作为ejs变量传递,但它不起作用