Google Maps中的多个标记Api无法读取未定义的属性“lat”

时间:2016-02-20 09:21:49

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

我有一个对象数组,我在地图上放置标记。所有的项都被检索,但是我在“bounds.extend(myLatLng [i]);”上收到“无法读取未定义的属性'lat'的错误”; 你能看出原因吗

function _studentsNearBySuccess(data) {
                    vm.notify(function () {
                        vm.studentsNearBy = data.items;
                        for (var i = 0; i < vm.studentsNearBy.length; i++) {
                            var myLatLng = new google.maps.LatLng(vm.studentsNearBy[i].latitude, vm.studentsNearBy[i].longitude);
                            var bounds = new google.maps.LatLngBounds();
                            var marker = new google.maps.Marker({
                                position: myLatLng[i],
                                title: 'Student Near By named ' + vm.studentsNearBy[i].firstName,
                            });
                            bounds.extend(myLatLng[i]);
                            var mapOptions = {
                                zoom: 10,
                                center: myLatLng
                            }
                            vm.map = new google.maps.Map($('#map-canvas')[0], mapOptions);
                            marker.setMap(vm.map)

                            vm.map.fitBounds(bounds);

                            var infowindow = new google.maps.InfoWindow({
                                content: vm.studentsNearBy[i].firstName + vm.studentsNearBy[i].lastName + vm.studentsNearBy[i].email
                            });
                        }

1 个答案:

答案 0 :(得分:1)

当您执行以下操作时,您可以将myLatLng创建为单个LatLng:

var myLatLng = new google.maps.LatLng(vm.studentsNearBy[i].latitude, vm.studentsNearBy[i].longitude);

然而,当你这样做时,你会尝试将它称为LatLngs数组:

position: myLatLng[i],

bounds.extend(myLatLng[i]);

这不是一个阵列。只需将这两个更改为:

position: myLatLng,

bounds.extend(myLatLng);

更新:添加了您的新功能版本。看起来您正在为每个标记创建一个新地图。我假设你只想要一张地图,而不是每个学生一张?并移动了创建LatLngBounds的代码,然后使地图适合循环外的那些边界。您仍然可以扩展循环中的边界。

function _studentsNearBySuccess(data) {
    vm.notify(function () {
        vm.studentsNearBy = data.items;
        var bounds = new google.maps.LatLngBounds();

        var mapOptions = {
            zoom: 10,
            center: myLatLng
        }
        vm.map = new google.maps.Map($('#map-canvas')[0], mapOptions);

        for (var i = 0; i < vm.studentsNearBy.length; i++) {
            var myLatLng = new google.maps.LatLng(vm.studentsNearBy[i].latitude, vm.studentsNearBy[i].longitude);

            var marker = new google.maps.Marker({
                map: vm.map,
                position: myLatLng,
                title: 'Student Near By named ' + vm.studentsNearBy[i].firstName,
            });
            bounds.extend(myLatLng);

            var infowindow = new google.maps.InfoWindow({
                content: vm.studentsNearBy[i].firstName + vm.studentsNearBy[i].lastName + vm.studentsNearBy[i].email
            });
        }

        vm.map.fitBounds(bounds);
    }
}