未定义不是Google Geolocation的功能

时间:2012-08-03 15:11:25

标签: javascript google-maps-api-3 google-geocoder

我正在尝试在我的网页中的Google地图元素上显示地址作为标记。

<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标记内生成脚本。

1 个答案:

答案 0 :(得分:4)

在API加载完成之前,您无法构造Geocoder对象。在initialize方法中或之后调用它。