【发布时间】:2020-03-30 11:29:37
【问题描述】:
不是最好的 javascript 并且在一些谷歌地图代码上遇到了一些问题,但它在 MS Edge 上是零星的,但在 Chrome 上是一致的,并且标记不会加载。如果您保持请求页面有时它会工作,但通常会失败。
错误:不是 LatLngBounds 或 LatLngBoundsLiteral:不是对象名称: “无效值错误”
使用以下代码调用脚本
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&libraries=places"></script>```
<script async type="text/javascript" src="{{media url='scripts/store-locator.js'}}"></script>```
require(["jquery"], function ($) {
$(document).ready(function () {
initialize();
});
var geocoder,
map,
markers = [],
infowindow = new google.maps.InfoWindow(),
bounds = new google.maps.LatLngBounds(),
marker, i;
var locations = [
{ id: 1, name: 'Store1', lat: 58.482514, lng: -1.784622 },
{ id: 2, name: 'Store2', lat: 54.687925, lng: 0.312584 }
];
function initialize() {
// set the default google map settings
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
var latlng = new google.maps.LatLng(52.727440, -1.543299);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// register the google map elements
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// register the directions display
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
addMarkers();
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// setup control position
control = document.getElementById('store-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
control.style.display = 'block';
});
}
// add the markers from the array to the map
function addMarkers() {
$.each(locations, function (key, value) {
// create the marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(this.lat, this.lng),
map: map,
name: this.name
});
// add the marker to the cached array
markers.push(marker);
bounds.extend(marker.position);
// add the event listerner for the marker click function
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// info window display
map.setZoom(16);
map.setCenter(marker.getPosition());
}
})(marker, i));
});
}
});```
【问题讨论】:
-
听起来像是时间问题。你是如何包含 API 的?请提供一个 minimal reproducible example 来证明您的问题。
-
posted code 对我来说似乎可以正常工作(至少在 Chrome 中,我无法访问 Edge ATM,我也没有
store-locator.js)。请提供一个 minimal reproducible example 来证明您的问题。 -
究竟是哪一行触发了错误?
-
store-locator.js 代码如上所示..只是在单独的文件中调用
标签: javascript google-maps google-maps-markers