[英]Why is this code throwing 'google not defined' error and also 'TypeError: Cannot read property 'PlacesService' of undefined at initialize' - error?
I am trying to have a google map api with markers showing nearby restaurants/cafes.我正在尝试使用带有标记的谷歌地图 api 显示附近的餐馆/咖啡馆。 I keep getting the following 2 errors:
我不断收到以下 2 个错误:
Uncaught ReferenceError: google is not defined at index.html:47未捕获的 ReferenceError:google 未在 index.html:47 中定义
Uncaught (in promise) TypeError: Cannot read property 'PlacesService' of undefined at initialize (index.html:26) at js?key=[API key]&callback=initialize&libraries=&v=weekly:142 at js?key=[API key]&callback=initialize&libraries=&v=weekly:142 Uncaught (in promise) TypeError: 无法在 js?key=[API key]&callback=initialize&libraries=&v=weekly:142 at js?key=[API key] 处读取未定义的属性“PlacesService” ]&callback=initialize&libraries=&v=每周:142
Why am I getting this error and how can I make it work?为什么我会收到此错误以及如何使其正常工作?
html, body, #map{ height: 100%; margin: 0; padding: 0; }
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="initial-scale=1.0, user-scalable=no"> <title>Restaurant</title> <link rel="stylesheet" href="style.css"> <script async defer src="https://maps.googleapis.com/maps/api/js?key=API KEY=initialize&libraries=&v=weekly"></script> <script> function initialize() { var center = new google.maps.LatLng(53.349804, -6.260310); map = new google.maps.Map(document.getElementById('map'), { center: center, zoom: 12, }); var request = { location: center, radius: 8047, types: ['cafe'] }; var service = new google.maps.places.PlacesService(map); service.nearbySearch(request, callback); } function callback(results, status) { if(status == google.maps.places.PlaceServiceStatus.OK) { for (var i =0; i < results.length; i++) { createMarker(results[i]); } } } function createMarker(place) { var placeLoc = place.geometry.location; var marker = new google.mpas.Marker({ map: map, position: place.geometry.location }); } google.maps.event.addDomListener(window, 'load', initialize); </script> </head> <body> <div id="map"> </div> </body> </html>
What is happening is that your inline script is firing immedietly as its parsed.发生的事情是您的内联脚本在解析时立即触发。 At that point the script you need from maps has not loaded yet.
此时,您需要从地图中获取的脚本尚未加载。 Infact it will only load once the rest of the page has been parsed.
事实上,它只会在页面的其余部分被解析后加载。
To fix this, shift your inline code into a .js
file and load it like you are the maps file, in a script
tag with a src
pointing to your file and a defer
attribute.要解决此问题,请将您的内联代码转换为
.js
文件并像加载地图文件一样加载它,在script
标记中使用一个src
指向您的文件和一个defer
属性。 Ensure the script tag for this comes after the request for the maps file确保此脚本标记出现在对地图文件的请求之后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.