Javascript"初始化"没有定义,但功能在那里

时间:2014-05-02 15:25:25

标签: javascript google-maps-api-3

我正在尝试加载带有多个标记的谷歌地图。此代码在onload中调用:

    <body onload="initialize()">

以下是有问题的javascript,位于<script>部分:

    var map; 
    var address = String("Chicago, Illinois")+" USA"; 
    var lat = null; 
    var long = null;
    var country = null; 
    var geocoder = new google.maps.Geocoder();
    var oms = new OverlappingMarkerSpiderfier(map,{markersWontMove: true, markersWontHide: true, keepSpiderfied: true});
    var iw = new google.maps.InfoWindow();
    oms.addListener('click',function(marker) {
        iw.setContent(marker.desc);
        iw.open(map,marker);
    });

    var contentString = '+String("Soldier Field")+"<br>"+latlng+'
    var infowindow =  new google.maps.InfoWindow();
    var marker, i, markerAddress;
    var facilities = "Soldier Field"; 
    var cities = "Chicago";
    var states = "Illinois"; 
    var coords = "41.862338,-87.615855";
    var phones = "312-235-7000"; 
    var url = "www.soldierfield.net"; 
    var briefText = "descriptive text"; 
    var lastUpdated = "2014-05-02"; 
    var overallContactName = "John Smith";
    var overallContactPhone = "312-235-7000"; 
    var overallContactEmail = "john.smith@email.com"; 
    var latlngStr;
    var image = {
        url: 'https://www.google.com/mapfiles/kml/paddle/ylw-stars.png',
        size: new google.maps.Size(40, 40),
    };

    var address_components = null;
    var tmpResult = null;
    var markers = []


    function initialize() { 

        var latlng = new google.maps.LatLng("41.862338", "-87.615855");
        //check if address in the US
        $.ajax({
            url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+{{lat}}+','+{{long}}+'&sensor=false',
            async: false,
            dataType: 'json',
            success: function(data) {
                $.each(data.results[0].address_components, function(index,comp) {
                    if (comp.types == 'country,political') {
                        country = comp.short_name;
                        return;
                    }
                });
            }
        });
        if (country == "US") { 
            var mapOptions = {zoom: 8,center: latlng, scrollwheel: false,}; 
            map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

            var circle = new google.maps.Circle({
                center: latlng,
                radius: {{search_distance}} * 1609.34,
                strokeColor: "#0000FF",
                strokeOpacity: 0.6,
                strokeWeight: 0.5,
                fillColor: "#0000FF",
                fillOpacity: 0.05,
               });          
            circle.setMap(map);
            map.fitBounds(circle.getBounds()); 
            drop(); // drop pins! 
            }
    } // map initialized 

    function geocode(facility,city,state) {
        $.ajax({
                    url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(facility)+"+"+encodeURIComponent(city)+"+"+encodeURIComponent(state)+'&sensor=false',
                    async: false,
                    dataType: 'json',
                    success: function(data) {
                        console.log('https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(facility)+"+"+encodeURIComponent(city)+"+"+encodeURIComponent(state)+'&sensor=false')
                        console.log(data.status)
                        lat = data.results[0].geometry.location.lat;
                        lng = data.results[0].geometry.location.lng;
                        address_components = data.results[0].address_components; 

                    }
                })
        return [lat, lng, address_components]; 
    }
    function drop() { 

        for (j = 0; j < facilities.length; j++) {
            setTimeout(function() {
                addMarker(); 
            }, j*200);
        }
    }
    function addMarker() {
        latlngStr = coords[j].split(","); 
        tmpResult = geocode(facilities[j],cities[j],states[j]);
        lat = tmpResult[0]
        lng = tmpResult[1]
        address_components = tmpResult[2]

        // clever solution to parse address_components: http://stackoverflow.com/a/16429122/3058197
        var components = {}; 
        jQuery.each(address_components, function(k,v1) {jQuery.each(v1.types, function(k2, v2){components[v2]=v1.long_name});})

        latlng = new google.maps.LatLng(lat,lng); 
        marker = new google.maps.Marker({
            position: latlng,
            map: map,
            title: facilities[j],
            animation: google.maps.Animation.DROP,
            }));
        oms.addMarker(marker);
        markers.push(marker); 
    }

我在javascript控制台中看到的错误是:

ReferenceError: initialize is not defined

有什么想法吗?感谢

4 个答案:

答案 0 :(得分:1)

尝试将此添加到您的代码中:

document.getElementsByTagName('body')[0].onload = initialize;

这可能超出了范围。

答案 1 :(得分:0)

可能的问题是:

  1. 您有一个脚本错误,会停止解析您的脚本,因此错误之后的所有内容都是未定义的。检查错误控制台以查找脚本解析错误并修复所有找到的错误。除非您使用的某种模板引擎替换了这些,否则这样的代码不合法​​javascript:var cities = {{cities}};

  2. 您的函数initialize()未在全局范围内定义(它必须是来自onload属性的初始化)。如果是这种情况,那么您需要为onload分配不同的内容,以便您可以使用不在全局范围内的函数或将其移动到全局范围。


  3. 仅供参考,因为你似乎已经在使用jQuery,你可以使用jQuery中的内置功能而不是等待onload:

    $(document).ready(initialize);
    

    虽然这只会解决你的问题,如果它是#2以上(并且你将这行代码放在与initialize函数相同的范围内),而不是问题是上面的#1。


    P.S。如果你共享一个正在运行的页面链接,我们可以在几分钟内解决这个问题,而不仅仅是猜测。

答案 2 :(得分:0)

不确定为什么它不调用你的函数,但是,我通常使用以下方法来调用初始化方法......

<html>
<head>
...
</head>
<body>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
  function initialise(){
     ...
  }
  google.maps.event.addDomListener(window, 'load', initialise); 
</script>
...

答案 3 :(得分:0)

@ user3058197:您的代码中存在大量错字错误和误解。

请查看以下

Line 14: var contentString --- Missing semicolon.
Line 31: size: , --- Extra comma at the last line.
Line 36: var markers  --- Missing semicolon.
Line 44: Dont pass null values better use the following

var latLng = new google.maps.LatLng("41.862338", "-87.615855");
//check if address in the US (The below is better than your previous code) 
$.ajax({
url: 'https://maps.googleapis.com/maps/api/geocode/json?latlng='+ latLng
+'&sensor=false'});
Line 57: var mapOptions = {,}; --- Extra comma at the end of the json object.

我刚才指出了一些事情。请使用firebug调试您的javascript代码。请仔细阅读documentation