首先,我想说我对Google Maps Javascript API v3
没有太多经验(我过去3天的唯一体验)。我设法显示带有标记列表的地图并使用DirectionsService
连接它们,但有时我的列表非常大,我收到以下错误:
Failed to load resource: the server responded with a status of 413 (Request Entity Too Large)
这是我的代码:
// List of all locations for device
var locations = [];
// example: locations = [
// {datetime: '2014/09/28 20:20', location: '41.99999 21.99999 30.0'},
// ... {...} ... may be more than 200 entries for locations
// {datetime: '2014/09/28 20:25', location: '41.99999 21.99999 30.0'}
// ]
var map;
var markers = [];
var bounds = new google.maps.LatLngBounds();
var pathPoints = [];
var infoWindow = new google.maps.InfoWindow();
var accuracy = new google.maps.Circle({
fillColor: '#ff4080',
fillOpacity: 0.5,
strokeOpacity: 0,
zIndex: 0
});
var path = new google.maps.Polyline(polyOptions);
var geocoder;
var directionsService = new google.maps.DirectionsService();
var directionsDisplay;
var polyOptions = {
geodesic: true,
strokeColor: '#28b8b8',
strokeOpacity: 1.0,
strokeWeight: 8,
zIndex: 1
}
function showInfoWindow(marker, datetime, acc){
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
infoWindow.close();
var date = datetime.split(" ")[0];
var time = datetime.split(" ")[1];
var content = '<div class="infowindow">'
+ results[1].formatted_address.trim() + '<br />'
+ 'Date: ' + date + '<br />'
+ 'Time: ' + time + '<br />'
+ 'Accuracy: ' + acc + 'm'
+ '</div>';
infoWindow.setContent(content);
infoWindow.open(map, marker);
accuracy.setMap(null);
accuracy.setMap(map);
accuracy.setCenter(marker.getPosition());
accuracy.setRadius(acc/1.6);
} else {
// alert('No results found');
}
} else {
alert('Geocoder failed due to: ' + status);
}
});
}
function addMultiMarker(latLng, num, datetime, acc){
// Create marker at provided location
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image_circle,
title: 'Location #' + num,
zIndex: num + 1
});
// On marker click center it inside map and show infoWindow
google.maps.event.addListener(marker, 'click', function() {
map.panTo(marker.getPosition());
showInfoWindow(marker, datetime, acc);
});
return marker;
}
function showRoute() {
var rendererOptions = {
draggable: false,
hideRouteList: true,
suppressMarkers: true,
infoWindow: infoWindow,
polylineOptions: polyOptions,
map: map
};
directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
var len = markers.length;
var start = markers[0].getPosition();
var end = markers[len - 1].getPosition();
new google.maps.event.trigger(markers[len - 1], 'click');
var wayPts = [];
for(var i = 1; i < len - 1; i++){
wayPts.push({
location: markers[i].getPosition(),
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: wayPts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
}
function showMapPeriod(periodStart, periodEnd){
// Simple map options
var mapOptions = {
zoom: 15,
center: new google.maps.LatLng(41, 21),
mapTypeId : google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
panControl: false,
streetViewControl: false
};
$("#map").html("");
// Create and show map
openMapContainer(); // just a function that shows the map <div> element
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Create and display markers
bounds = new google.maps.LatLngBounds();
markers = [];
var len = 0;
for(var i = periodStart; i <= periodEnd; i++, len++){
var loc_vals = locations[i].location.trim().split(" ");
var lat = parseFloat(loc_vals[0]);
var lng = parseFloat(loc_vals[1]);
var acc = parseFloat(loc_vals[2]);
// Create marker at provided location
var datetime = locations[i].datetime;
var latLng = new google.maps.LatLng(lat, lng);
markers[len] = addMultiMarker(latLng, len+1, datetime, acc);
bounds.extend(latLng);
}
showRoute();
map.fitBounds(bounds);
}
我的代码部分工作,如果有人可以帮我解决问题,我会非常感激。为了更好地解释它,我需要某种解决方案来请求Directions
有很多(200+)个航路点或某种方式通过道路连接位置(我真的不需要指示,但我不是'我想用简单的Polyline
)连接位置。
编辑:Here我提供了一个简单的演示,以便在line 15
取消注释问题。
答案 0 :(得分:5)
由于没有人能够帮我解决问题,我必须自己解决。我正在回答我自己的问题,因为对于很多人来说这似乎是一个很大的问题,而且在网上解释得不够好,所以这可能会对有类似问题的开发人员有所帮助。
无论如何,让我们明白这一点。由于Google建议使用OxyDesign限制而引发错误,错误是:
google.maps.DirectionsResult.MAX_WAYPOINTS_EXCEEDED
- 这是因为我发送的请求包含 origin , destination 以及超过8个(Google限制)航路点 我很容易解决(我只是将数组拆分为10个点,其中一个请求的最后一个点作为下一个请求的第一个点),但后来又出现了另一个错误:
google.maps.DirectionsResult.OVER_QUERY_LIMIT
- 这是因为我尝试每秒发送超过10个(再次是Google限制)请求。进行了一些实验,搜索和测试以解决问题,但我解决了这个问题。
现在,这是适用于我的代码(至少在发布时,直到Google更改内容):
// list of randomly generated locations (max 288)
var locations = [];
for(var i=0; i<288; i++){
locations[i] = {
datetime: '2014/10/01 12:10',
location: (51 + Math.random()) +
' ' + (-0.5 + Math.random()) + ' 30.0'
};
}
// Marker images
var image_pin = new google.maps.MarkerImage(
'http://stedkomerc.com.mk/gpslocator/images/mPin.svg',
new google.maps.Size(25, 41), // size
new google.maps.Point(0, 0), // origin, top-left corner
new google.maps.Point(12, 40) // anchor
);
var image_circle = new google.maps.MarkerImage(
'http://stedkomerc.com.mk/gpslocator/images/mCircle.svg',
new google.maps.Size(19, 19), // size
new google.maps.Point(0, 0), // origin, top-left corner
new google.maps.Point(9, 9) // anchor
);
// Variables
var map;
var bounds = new google.maps.LatLngBounds();
var markers = [];
var pathPoints = [];
var geocoder;
var infoWindow = new google.maps.InfoWindow();
var accuracy = new google.maps.Circle({
fillColor: '#ff4080',
fillOpacity: 0.4,
strokeOpacity: 0,
zIndex: 0
});
var polyOptions = {
geodesic: true,
strokeColor: '#28b8b8',
strokeOpacity: 1.0,
strokeWeight: 8,
zIndex: 1
};
var path = new google.maps.Polyline(polyOptions);
var directionsService = new google.maps.DirectionsService();
var directions = [];
var rendererOptions = {
draggable: false,
hideRouteList: true,
suppressMarkers: true,
preserveViewport: true,
infoWindow: infoWindow,
polylineOptions: polyOptions
};
var requests = [];
var MAX_POINTS_PER_REQUEST = 10; // 8*waypts Google limit + start + end
var MAX_REQUESTS_PER_SECOND = 10; // Google limit
// functions
function showInfoWindow(marker, datetime, acc){
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'latLng': marker.getPosition()
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[1]) {
infoWindow.close();
var date = datetime.split(" ")[0];
var time = datetime.split(" ")[1];
var content = '<div class="infowindow">' +
results[1].formatted_address.trim() + '<br />' +
'Date: ' + date + '<br />' +
'Time: ' + time + '<br />' +
'Accuracy: ' + acc + 'm' +
'</div>';
infoWindow.setContent(content);
infoWindow.open(map, marker);
accuracy.setMap(null);
accuracy.setMap(map);
accuracy.setCenter(marker.getPosition());
accuracy.setRadius(acc);
}
} else {
console.log('Geocoder failed due to: ' + status);
}
});
}
function addMultiMarker(latLng, num, datetime, acc){
// Create marker at provided location
var marker = new google.maps.Marker({
position: latLng,
map: map,
icon: image_circle,
title: 'Location #' + num,
zIndex: num + 1
});
// On marker click center it inside map and show infoWindow
google.maps.event.addListener(marker, 'click', function() {
//map.panTo(marker.getPosition());
showInfoWindow(marker, datetime, acc);
});
return marker;
}
function connectMarkersPolyline(mrkrs){
path.setMap(map);
pathPoints = path.getPath();
len = mrkrs.length;
for(var i = 0; i < len; i++){
pathPoints.push(mrkrs[i].getPosition());
}
}
function connectMarkersRoute(mrkrs, part, maxParts){
var directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
directionsDisplay.setMap(map);
var len = mrkrs.length;
var start = mrkrs[0].getPosition();
var end = mrkrs[len - 1].getPosition();
var wayPts = [];
for(var i = 1; i < len - 1; i++){
wayPts.push({
location: mrkrs[i].getPosition(),
stopover: true
});
}
var request = {
origin: start,
destination: end,
waypoints: wayPts,
optimizeWaypoints: false,
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
// request status OK, display route
directionsDisplay.setDirections(response);
// save it in array in case we want to remove it later
directions.push(directionsDisplay);
// if not last chunk, send next chunk after 100ms
// 1 request per 100ms => 10 requests per 1s
if(part+1 < maxParts)
setTimeout(connectMarkersRoute(requests[part+1], part+1, maxParts), 100);
else showLastMarker();
} else if (status == google.maps.DirectionsStatus.OVER_QUERY_LIMIT) {
// if we get error, send same request after bigger delay (120ms)
setTimeout(connectMarkersRoute(requests[part], part, maxParts), 120);
} else {
// if all fails, connect with simple polyline
console.log('Directions failed due to: ' + status);
connectMarkersPolyline(mrkrs);
}
});
}
function connectMarkers(markers){
path.setMap(null);
path.setPath([]);
directions = [];
requests = [];
var len = markers.length;
console.log('connecting ' + len + ' markers');
var i, j;
// split markers array into chunks of 10 (start + waypts + end)
for(i=0; i<len; i+=MAX_POINTS_PER_REQUEST-1){
if(i<len-1)
requests.push(markers.slice(i, i+MAX_POINTS_PER_REQUEST));
}
// send first chunk to connectMarkersRoute()
connectMarkersRoute(requests[0], 0, requests.length);
}
function showMapPeriod(periodStart, periodEnd){
// Map options
var mapOptions = {
zoom: 16,
center: new google.maps.LatLng(41.995922, 21.431465),
mapTypeId : google.maps.MapTypeId.ROADMAP,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE,
position: google.maps.ControlPosition.LEFT_CENTER
},
panControl: false,
streetViewControl: false
};
$("#map").html("");
//openMapContainer();
// Create and show map
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// Create and display markers
bounds = new google.maps.LatLngBounds();
markers = [];
var len = 0;
for(var i = periodStart; i <= periodEnd; i++, len++){
var loc_vals = locations[i].location.trim().split(" ");
var lat = parseFloat(loc_vals[0]);
var lng = parseFloat(loc_vals[1]);
var acc = parseFloat(loc_vals[2]);
// Create marker at provided location
var datetime = locations[i].datetime;
var latLng = new google.maps.LatLng(lat, lng);
markers[len] = addMultiMarker(latLng, len+1, datetime, acc);
bounds.extend(latLng);
}
connectMarkers(markers);
map.fitBounds(bounds);
if(map.getZoom() > 16) map.setZoom(16);
}
function showLastMarker(){
new google.maps.event.trigger(markers[markers.length - 1], 'click');
}
// show map
showMapPeriod(1, 280);
// --------
正如您所看到的,我所做的唯一真正的改变是showRoute()
函数变为connectMarkers()
并结合connectMarkersRoute()
和connectMarkersPolyline()
来处理这两个错误。
可以看到工作示例here。加载所有路径块需要一点时间,但至少它可以工作。希望这也有助于其他人。
请注意,Google每天还会有2500 Directions
次请求限制,因此请务必小心。话虽如此,这个答案甚至适用于比200个地点更多的请求,我已经测试了1250个地点并且它有效。
答案 1 :(得分:3)
此服务似乎有限制Gmaps Waypoints( 8 或 23 ,我尝试过它直到39,然后40没有)除了使用折线之外没有办法以其他方式做到这一点,但你不想要它,所以我认为没有可行的解决方案......