未捕获的TypeError:无法读取地图5中未定义的属性“setCenter”

时间:2016-07-13 14:01:43

标签: javascript google-maps-api-3

// this function search location and show on map

function showAddressTextBox(address) { //    showAddressTextBox function search location and show on map 
    //    alert(address);
    var infowindow2 = new google.maps.InfoWindow(); //this infowindows
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            map.setCenter(results[0].geometry.location);
            var marker = new google.maps.Marker({
                map: map,
                position: results[0].geometry.location
            });
            google.maps.event.addListener(marker, 'click', function () {
                infowindow2.setContent('<div><strong>Address:' + results[0].formatted_address + '</strong><br>' +
                    'Place ID: ' + results[0].place_id + '</div>');
                infowindow2.open(map, marker);
            });
            //            path = address;
            //            lat = results[0].geometry.location.lat();
            //            lon = results[0].geometry.location.lng();
        } else {
            //alert("Geocode was not successful for the following reason: " + status);
        }
    });
} //end function

1 个答案:

答案 0 :(得分:0)

非常简单,您的map变量未定义!

您没有显示整个代码吗?定义map变量在哪里?

该示例显示您必须定义map变量并初始化实际地图。

var map;
function initialize() {
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(-34.397, 150.644);
    var mapOptions = {
      zoom: 8,
      center: latlng
    }
    map = new google.maps.Map(document.getElementById("map"), mapOptions);
  }

在此处查看更多内容:https://developers.google.com/maps/documentation/javascript/geocoding