2017-08-28 91 views
0

我正在渲染maps.ejs文件:place_id,lat,lng。爲什麼我無法在谷歌地圖API中呈現「place_id」到ejs文件?

如果我在initMap函數本身的maps.ejs文件中聲明瞭「place_id」,那麼代碼運行良好,沒有任何錯誤。 但是,當我渲染place_id如圖所示的代碼它給誤差在鉻的控制檯:

(指數):34未捕獲的ReferenceError:

I:ChIJN1t_tDeuEmsRUsoyG83frY4不是在initMap(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>

回答

0

地圖API是一個Web瀏覽器 API。如果您想將它作爲Express服務器應用程序的一部分進行調試,您只需設置自己的麻煩即可。

請改用瀏覽器查看生成的代碼,或者使用View Source或使用瀏覽器的開發人員工具。這將大大簡化您的調試。一旦生成的HTML和JavaScript代碼碰到瀏覽器,服務器代碼就完全不相關。

這就是說,你跑進特定的錯誤很可能是由於你的maps.ejs文件這行代碼:

placeId: <%=place_id%> 

,當您在瀏覽器中做了查看源代碼,你會看到,代碼快報在這裏產生的大概是:

placeId: ChIJN1t_tDeuEmsRUsoyG83frY4 

換句話說,在JavaScript的瀏覽器看到ChIJN1t_tDeuEmsRUsoyG83frY4作爲變量名,不是文字串,你可能需要在這裏。

爲了解決這個問題,簡單地把ID引號:

placeId: "<%=place_id%>" 

現在生成的代碼將是:

placeId: "ChIJN1t_tDeuEmsRUsoyG83frY4" 

現在placeId將是一個字符串,如預期。

+0

我試着創建一個字符串變量place_id但那也不起作用。 我的壞... Thankyou非常.. 這是一個愚蠢的問題。 –

+0

不是一個愚蠢的問題。而且不要感覺不好 - 這種情況發生在我們所有人身上的時候!我發現這麼快的原因是我自己犯了同樣的錯誤。 ;-)讓我知道這是否是問題所在。 –