Undefined is not a function, Google Geolocation

僤鯓⒐⒋嵵緔 提交于 2019-12-01 06:53:54

问题


I'm trying to display an address as a marker on a google map element within my page.

<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>

But, on this line

var geocoder = new google.maps.Geocoder();

I am getting an uncaught type error of "Undefined is not a function."

I've omitted my api key in this selection of my code, as well as changed the address from what I am using to test. (my home address)

Also, I am using ASP.NET to generate the script within the span tags.


回答1:


You can't construct the Geocoder object before the API has finished loading. Call it in or after your initialize method.



来源:https://stackoverflow.com/questions/11798431/undefined-is-not-a-function-google-geolocation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!