我在.js脚本(对于谷歌地图)有问题,在另一个视图中这个脚本正常工作(但我们的位置很少)
我有这样的错误
未捕获的TypeError:addresses.forEach不是函数
at getAllAddresses (map-localizations.js:26) at setMarkersOnMap (map-localizations.js:49) at Object.<anonymous> (map-localizations.js:19) at fire (jquery.js:3317) at Object.fireWith [as resolveWith] (jquery.js:3447) at done (jquery.js:9272) at XMLHttpRequest.<anonymous> (jquery.js:9514)
我使用的map-localizations.js文件
$(document).ready(function() {
var $googleMap = $('.google-map');
var map = new google.maps.Map($googleMap[0], {
zoom: 0,
center: {lat: 0, lng: 0}
});
initMap();
function initMap() {
var geocoder = new google.maps.Geocoder();
$.ajax({
type: 'POST',
dataType: 'json',
url: '/ajax/company-localizations',
data: {id: $googleMap.data('id')}
}).done(function(addresses) {
setMarkersOnMap(addresses, geocoder);
});
}
function getAllAddresses(geocoder, addresses) {
var deferreds = [];
addresses.forEach(function(address) {
if (!address.hasOwnProperty('error')) {
deferreds.push(geocodeAddress(geocoder, address));
}
});
return deferreds;
}
function geocodeAddress(geocoder, address) {
var deferred = $.Deferred();
geocoder.geocode({'address': address}, function(results, status) {
deferred.resolve(results[0]);
});
return deferred.promise();
}
function cutUndefined(element, index, array) {
return (typeof element !== 'undefined')
}
function setMarkersOnMap(addresses, geocoder) {
var deferreds = getAllAddresses(geocoder, addresses);
$.when.apply($, deferreds).then(function() {
var bounds = new google.maps.LatLngBounds();
var locations = Array.prototype.slice.call(arguments).filter(cutUndefined);
var markers = [];
locations.forEach(function(location, index) {
bounds.extend(location.geometry.location);
markers.push(
new google.maps.Marker({
map: map,
position: location.geometry.location,
status: 'active',
zoom: 10,
label: location.formatted_address
})
)
});
map.fitBounds(bounds);
map.panToBounds(bounds);
var markerCluster = new MarkerClusterer(
map,
markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'}
);
});
}
});
我已将我的js文件附加到我的视图
$this->registerJsFile('js/map-localizations.js',
[
'depends' => [\yii\web\JqueryAsset::className(), \yii\web\YiiAsset::className()],
'position' => \yii\web\View::POS_END
]);
并在页面上显示
<div id="localizations-map" class="google-map" google-maps data-id="" data-address="<?php echo $company->street; ?>, <?php echo $company->house_no; ?> <?php $company->local_no ? '/' . $company->local_no : ''; ?> <?php echo $company->postal_code; ?> <?php echo $company->cityEntity->cityEntity->name; ?>">
</div>