我不确定如何在不在我的HTML页面中的脚本之外加载我的Google Maps API代码。
我收到错误:
Error: google is not defined
Source File: http://localhost:3000/javascripts/google-map.js?1319030830
Line: 57
这就是它所说的话:
google.maps.event.addDomListener(window, 'load', initialize);
以下是我的google-map.js
文件的完整代码:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng( 37.09024 ,-95.712891 ),
zoom: 1,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('google_map'),
mapOptions);
var input = document.getElementById('business_retail_address');
var options = { types: ['geocode']};
autocomplete = new google.maps.places.Autocomplete(input, options);
autocomplete.bindTo('bounds', map);
var infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map
});
google.maps.event.addListener(autocomplete, 'place_changed', function() {
infowindow.close();
var place = autocomplete.getPlace();
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(16); // Why 17? Because it looks good.
}
var image = new google.maps.MarkerImage(
place.icon,
new google.maps.Size(71, 71),
new google.maps.Point(0, 0),
new google.maps.Point(17, 34),
new google.maps.Size(35, 35));
marker.setIcon(image);
marker.setPosition(place.geometry.location);
var address = '';
if (place.address_components) {
address = [(place.address_components[0] &&
place.address_components[0].short_name || ''),
(place.address_components[1] &&
place.address_components[1].short_name || ''),
(place.address_components[2] &&
place.address_components[2].short_name || '')
].join(' ');
}
infowindow.setContent();
infowindow.open(map, marker);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
我现在对Javascript了解不多,所以我迷失了如何正确加载它或如何在 JS 文件本身中编写函数。
如何将此google脚本正确放入JS文件中?
谢谢。
答案 0 :(得分:1)
您是否在页面中的脚本之前加载了Google地图脚本?看起来你可能不是。
你需要
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
然后你的脚本参考
<script type="text/javascript" src="your-script.js"></script>
将其放在<head>
部分或结束</body>
标记之前。