How to acess JSON object inside a script tag?

Viewed 106

I have an API call to google directions API and then i am trying to save that JSON response in a variable called as lat through this code

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);

Now, inside my ejs file i want to pass this response inside a script tag in order to render a map.

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>

i have tried passing that variable as a ejs variable but its not working

0 Answers
Related