[英]Google Maps API: How can I turn a `place_id` into geocoordinates?
[英]Why can't I render “place_id” in google maps api to an ejs file?
我正在渲染maps.ejs文件,其中包含:place_id,lat,lng。
如果我在initMap函數本身的maps.ejs文件中聲明“ place_id”,則代碼運行正常,沒有任何錯誤。 但是,當我按代碼所示渲染place_id時,它在chrome的控制台中給出了錯誤:
(索引):34未捕獲的參考錯誤:initMap上未定義ChIJN1t_tDeuEmsRUsoyG83frY4((索引):34)
我正在使用cloud9並已將API_KEY導出為環境變量。
//app.js var express = require("express"); var app = express(); app.get("/", function(req, res) { res.render("maps.ejs", { place_id: "ChIJN1t_tDeuEmsRUsoyG83frY4", lat: -33.8666199, lng: 151.1958527 }); }); app.listen(process.env.PORT, process.env.IP, function() { console.log("Server is ON"); }); // Server start
//maps.ejs <!DOCTYPE html> <html> <head> <style> #map { height: 400px; width: 100%; } </style> </head> <title>Google Maps API</title> <body> <h3>My Google Maps Demo</h3> <script> function initMap() { var uluru = { lat: <%=lat%>, lng: <%=lng%> }; var map = new google.maps.Map(document.getElementById('map'), { zoom: 14, center: uluru }); var infowindow = new google.maps.InfoWindow(); var service = new google.maps.places.PlacesService(map); service.getDetails({ placeId: <%=place_id%> }, function(place, status) { console.log(place); if (status === google.maps.places.PlacesServiceStatus.OK) { var marker = new google.maps.Marker({ map: map, position: place.geometry.location }); google.maps.event.addListener(marker, 'click', function() { infowindow.setContent( '<div><strong>' + place.name + '</strong><br>' + 'Place ID: ' + place.place_id + '<br>' + place.formatted_address + '<br>' + "Rating : " + place.rating + '</div>'); infowindow.open(map, this); }); } }); </script> <script async defer src="https://maps.googleapis.com/maps/api/js?key=<%=process.env.API_KEY%>&libraries=places&callback=initMap"> </script> <div id="map"></div> </body> </html>
Maps API是網絡瀏覽器 API。 如果您想將其調試作為Express服務器應用程序的一部分,就只會給自己帶來麻煩。
相反,看看在瀏覽器中生成的代碼,無論是與查看源代碼或使用瀏覽器的開發者工具。 這將大大簡化您的調試。 一旦生成的HTML和JavaScript代碼到達瀏覽器,服務器代碼就完全不相關了。
也就是說,您遇到的特定錯誤很可能是由於maps.ejs
文件中的以下代碼行造成的:
placeId: <%=place_id%>
正如您在瀏覽器中執行“查看源代碼”時所看到的那樣,Express此處生成的代碼可能是:
placeId: ChIJN1t_tDeuEmsRUsoyG83frY4
換句話說,瀏覽器中的JavaScript將ChIJN1t_tDeuEmsRUsoyG83frY4
視為變量名 ,而不是您可能需要的文字字符串。
要解決此問題,只需將ID放在引號中:
placeId: "<%=place_id%>"
現在生成的代碼將是:
placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4"
現在placeId
將是預期的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.