我正在尝试在页面内的google map元素上显示一个地址作为标记。
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=my_key&sensor=true&callback=initialize"></script>
<script language="javascript" type="text/javascript">
navigator.geolocation.getCurrentPosition(foundLocation, noLocation);
var latitude;
var longitude;
var map;
function foundLocation(position) {
latitude = position.coords.latitude;
longitude = position.coords.longitude;
}
function noLocation() {
//Do something here in the case that no location is found, or user denies access
}
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//setMarkers();
}
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markersArray.push(marker);
}
</script>
<span id="ctl00_ContentPlaceHolder1_lblGeneratedScript"><script language="javascript" type="text/javascript">
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': "123 Test Dr."}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
addMarker(results[0].geometry.location);
} else {
alert("Geocode failed! Reason: " + status);
}
});
</script>
</span>
但是,在这条线上
var geocoder = new google.maps.Geocoder();
我收到了“未定义不是函数”的未捕获类型错误。
我在选择代码时省略了api密钥,并且更改了我要测试的地址。 (我的家庭住址)
另外,我正在使用ASP.NET在span标签内生成脚本。
最佳答案
您不能在API完成加载之前构造Geocoder对象。在initialize
方法中或之后调用它。