【发布时间】:2016-12-19 05:50:54
【问题描述】:
我正在尝试使用 google maps api 将我的地址转换为经度和纬度,然后在页面上显示地图。
请注意,我使用 PHP/Laravel 从数据库中检索地址。因此,尽管它是纽约的硬编码值,但在我开始工作后将是动态的。
HTML
<div id="map" style="height:250px"></div>
Javascript
<script>
var geocoder = new google.maps.Geocoder();
var address = "new york";
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var latitude = results[0].geometry.location.lat();
var longitude = results[0].geometry.location.lng();
alert(latitude);
}
});
function initMap() {
var myLatLng = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=keyremoved&callback=initMap">
</script>
目前我收到“Uncaught ReferenceError: google is not defined”的错误
【问题讨论】:
-
在调用
initMap之前,您正在执行代码的上半部分 - 一旦加载了谷歌地图 api,就会调用 initMap - 将上面的代码放在initMap内initMap和你会更接近实现你的目标 -
将地理编码器代码移动到
initMap函数中。您将在 maps js URI 的 URL 中看到一个回调函数。这将在加载地图脚本后执行。您在脚本加载之前调用 newgoogle.maps.Geocoder();