我正在尝试使用带有显示附近餐馆/咖啡馆的标记的 google map api。我不断收到以下 2 个错误:未捕获的 ReferenceError:未在 index.html:47 定义谷歌未捕获(承诺)TypeError:无法在 js?key=[API key]&callback=initialize&libraries=&v=weekly:142 at js?key=[API key] 处读取未定义的属性“PlacesService”(index.html:26) ]&callback=initialize&libraries=&v=weekly:142为什么我会收到此错误以及如何让它工作?html, body, #map{ height: 100%; margin: 0; padding: 0;}<!DOCTYPE html><html><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>
1 回答
偶然的你
TA贡献1841条经验 获得超3个赞
发生的事情是您的内联脚本在解析时立即触发。那时你需要的地图脚本还没有加载。事实上,它只会在页面的其余部分被解析后加载。
要解决此问题,请将您的内联代码转移到一个.js
文件中,并像加载地图文件一样加载它,在script
带有src
指向您的文件和defer
属性的标记中。确保此脚本标记出现在地图文件请求之后
添加回答
举报
0/150
提交
取消