javascript Google 静态地图 URL 长度限制
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4278053/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Google Static Maps URL length limit
提问by eos87
I have 153 markers and need to generate a static map with them, but when put them in the url I get an error like this:
我有 153 个标记,需要用它们生成一个静态地图,但是当将它们放入 url 时,我收到如下错误:
414 Request-Uri Too Large
My url is something like this
我的网址是这样的
"http://maps.google.com/maps/api/staticmap?center=13.00,-85.00&size=600x500&maptype=roadmap&markers=13.305,-86.18636&markers=13.72326,-86.13705&......"
Thanks folks!
谢谢各位!
采纳答案by scheffield
This response came from the Server (google). So you're not allowed to request such long URLs.
此响应来自服务器(谷歌)。所以你不能请求这么长的 URL。
See the google api doc for more infos:
有关更多信息,请参阅 google api 文档:
Static Map URLs are restricted to 2048 characters in size. In practice, you will probably not have need for URLs longer than this, unless you produce complicated maps with a high number of markers and paths.
静态地图 URL 的大小限制为 2048 个字符。在实践中,您可能不需要比这更长的 URL,除非您生成具有大量标记和路径的复杂地图。
回答by Argiropoulos Stavros
The way i see it is either you reduce precisionof your markers in order to gain space in the URL.
(i.e. markers=13.72326,-86.13705---->markers=13.73,-86.14) resulting in placing the markers in a grid...
Or you go with a non static api
我的看法是要么降低标记的精度以在 URL 中获得空间。(即markers=13.72326,-86.13705---->markers=13.73,-86.14)导致将标记放置在网格中......
或者你使用非静态api
回答by Edmhs
I had same problem,
我有同样的问题,
i used link like this, and reduced position precision:
我使用了这样的链接,并降低了位置精度:
回答by Mehran Khan
You can encode your Polylines and make them shorter .
您可以对折线进行编码并使它们更短。
Here is the example which can help you how to short your Polylines
这是可以帮助您缩短折线的示例
I am using the php library to short the length here is the link of library https://github.com/danmandle/encoded-polyline-stitcher
我正在使用 php 库来缩短长度,这里是库https://github.com/danmandle/encoded-polyline-stitcher的链接
if you use this library
如果你使用这个库
(51.838245,-111.834991|51.833179,-111.83503|51.831007022306,-111.8232751234|51.838244686875,-111.82327418214) = (atk{HtwqiTt^FpLmhAgl@)
Here important point is if you use short url you have to use "enc:"keyword
这里重要的一点是,如果您使用短网址,则必须使用“enc:”关键字
(fillcolor:0xAA000033|color:0xFFFFFF00|51.838245,-111.834991|51.833179,-111.83503|51.831007022306,-111.8232751234|51.838244686875,-111.82327418214) = (fillcolor:0xAA000033|color:0xFFFFFF00|enc:atk{HtwqiTt^FpLmhAgl@)
The Library is available for other languages as well if you are not using php .
如果您不使用 php ,该库也可用于其他语言。
I hope that it helps others
我希望它能帮助别人
回答by Ville N.
回答by Steve Jalim
回答by TMS
You might also use marker clustering on a static map:
您还可以在静态地图上使用标记聚类:
http://www.appelsiini.net/projects/php_google_maps/cluster.html
http://www.appelsiini.net/projects/php_google_maps/cluster.html
http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps
http://www.appelsiini.net/2008/11/introduction-to-marker-clustering-with-google-maps
回答by Crow
Officially you can use 8192 characters
官方可以使用 8192 个字符
This depends on browserand server, but as a thumb rule 8192 characters should be OK.
这取决于浏览器和服务器,但根据经验,8192 个字符应该没问题。
Server
服务器
Google Maps Static server https://maps.googleapis.com/maps/api/staticmapat 30 July 2019.
谷歌地图静态服务器https://maps.googleapis.com/maps/api/staticmap于2019 年 7 月 30 日。
Google Static Maps Docsclaims that:
Maps Static API URLs are restricted to 8192 charactersin size. In practice, you will probably not have need for URLs longer than this, unless you produce complicated maps with a high number of markers and paths. Note, however, that certain characters may be URL-encoded by browsers and/or services before sending them off to the API, resulting in increased character usage.
地图静态 API URL 的大小限制为8192 个字符。在实践中,您可能不需要比这更长的 URL,除非您生成具有大量标记和路径的复杂地图。但是请注意,某些字符可能会在将它们发送到 API 之前由浏览器和/或服务进行 URL 编码,从而导致字符使用量增加。
But in practice, I'm getting errors (413 Payload Too Large) after 15k~ characters mark (30 July 2019):
但实际上,在 15k~ 个字符标记(2019 年 7 月 30 日)之后,我收到错误(413 Payload Too Large ):
╔═════════╦═════════════════╦══════════════════╗
║ Browser ║ Browser Version ║ Valid URL Length ║
╠═════════╬═════════════════╬══════════════════╣
║ Chrome ║ 75 ║ 15489 ║
║ Firefox ║ 68 ║ 15761 ║
║ Safari ║ 12.1 ║ 15690 ║
╚═════════╩═════════════════╩══════════════════╝
This is based on data got by using fetch()in browser console. I'd assume that Google Static Maps server accepts requests (whole request, not just path) no larger than 16k in size.
这是基于fetch()在浏览器控制台中使用获得的数据。我假设 Google 静态地图服务器接受大小不超过 16k 的请求(整个请求,而不仅仅是路径)。
Solutions
解决方案
Reduce Precision
降低精度
Our company policy is that coordinate data below 6 decimal places(111.32 mm) is useless (considering our market share uses phones and commercial GPS devices).
我们公司的政策是小数点以下6 位(111.32 毫米)以下的坐标数据是无用的(考虑到我们的市场份额使用手机和商用 GPS 设备)。
const decimalPlaces = 6 // decimal places count
const decimalPowered = 10 ** decimalPlaces // 1_000_000
const trim = number => Math.round(number * decimalPowered) / decimalPowered // function that trims number
const coordinates = [
[51.838245, -111.834991],
[51.8331, -111.835],
[51.831007022306, -111.8232751234],
[51.838244686875, -111.82327418214]
]
const trimmedCoordinates = coordinates.map(coordinate => coordinate.map(trim))
console.log(trimmedCoordinates)
Encode coordinates
编码坐标
If you have access to encoder you can replace path with an encoded path (use Stringmanipulation instead of URLSearchParams, because searchParamsautomatically uses encodeURI, which would break your encoded path):
如果您有权访问编码器,您可以用编码路径替换路径(使用String操作而不是URLSearchParams,因为searchParams自动使用 encodeURI,这会破坏您的编码路径):
const coordinates = [
[51.838245, -111.834991],
[51.8331, -111.835],
[51.831007022306, -111.8232751234],
[51.838244686875, -111.82327418214]
].map(([lng, lat]) => ({ lng, lat }))
// path should be MVCArray<LatLng>|Array<LatLng>, if you have Polygon or Polyline, getPath() method should be fine
const path = coordinates.map(coordinate => new google.maps.LatLng(coordinate))
const encoded = google.maps.geometry.encoding.encodePath(
path
);
return (
url.href +
`&path=fillcolor:${color}|color:${color}|enc:${encoded}`
);
https://developers.google.com/maps/documentation/maps-static/dev-guidehttps://developers.google.com/maps/documentation/utilities/polylinealgorithmhttps://developers.google.com/maps/documentation/javascript/geometry#Encoding
https://developers.google.com/maps/documentation/maps-static/dev-guide https://developers.google.com/maps/documentation/utilities/polylinealgorithm https://developers.google.com/maps/文档/javascript/geometry#Encoding
Handle Errors
处理错误
- Use placeholder image
- Check if
href.length > 8192before request - Trim coordinates
- Encode path
- Check if
!res.ok && res.status === 413and display error for user which claims that map is too detailed - Use fallback image
- 使用占位符图片
- 检查是否
href.length > 8192在请求之前 - 修剪坐标
- 编码路径
- 检查
!res.ok && res.status === 413并显示用户声称地图太详细的错误 - 使用后备图片
回答by Andy Gee
Very old thread but I had to cobble together something to tackle this very problem in a hurry. Sharing here in case anyone else had the same problem.
非常旧的线程,但我不得不拼凑一些东西来快速解决这个问题。在这里分享以防其他人遇到同样的问题。
It takes an array of markers in the form:
它采用以下形式的一系列标记:
$points =
[0] => Array
(
[lat] => 52.1916312
[lng] => -1.7083109
)
[1] => Array
(
[lat] => 50.2681918
[lng] => 2.5616710
)
...
...
...
[500] => Array
(
[lat] => 49.1821968
[lng] => 2.1671056
)
Max url length is 2048 chars so it first reduces accuracy of the lat lng to $marker_accuracy (4) then starts removing markers from the middle. Removing markers from the middle could be improved a lot as it does it one at a time
最大 url 长度为 2048 个字符,因此它首先将 lat lng 的准确性降低到 $marker_accuracy (4),然后开始从中间删除标记。从中间去除标记可以得到很大改善,因为它一次一个
$map_url = make_static_map($points);
function make_static_map($points,$reduce_len=false,$reduce_count=false){
$grp_points = array();
$grps = array();
$url = array();
$max_len = 0;
$width = 640; //max 640 :(
$height = 640; //max 640 :(
$marker_accuracy = 4; //Lat lng to 4 decimal places minimum, 3 would be less accurate
$url[] = 'http://maps.googleapis.com/maps/api/staticmap?';
$url[] = '&size='.$width.'x'.$height.'&scale=2';
$url[] = '&markers=';
if($reduce_count){ //Last resort to shortening this
array_splice($points, ceil(count($points)/2), 1);
}
foreach($points as $i => $point){
if($reduce_len){
$point['lat'] = number_format($point['lat'], $reduce_len, '.', '');
$points[$i]['lat'] = $point['lat'];
$point['lng'] = number_format($point['lng'], $reduce_len, '.', '');
$points[$i]['lng'] = $point['lng'];
}else{
$t_len = max(strlen($point['lat']),strlen($point['lng']));
if($t_len>$max_len){
$max_len = $t_len;
}
}
$grps[] = array($point['lat'],$point['lng']);
}
$grps = remove_duplicate_points($grps);
foreach($grps as $grp){
$grp_points[] = implode(',',$grp);
}
$url[] = implode('|',$grp_points);
$url[] = '&sensor=false';
$url = implode('',$url);
if(strlen($url) > 2048){
// Bugger, too long for google
if($max_len>$marker_accuracy){
// Reduce the length of lat lng decimal places
return(make_static_map($points,$max_len-1,false));
}else{
// Reduce the number of lat lng markers (from center)
return(make_static_map($points,false,true));
}
}else{
return($url);
}
}
function remove_duplicate_points($points){
$points = array_map('serialize', $points);
$points = array_unique($points);
return(array_map('unserialize', $points));
}
回答by jperelli
Use osm-static-maps, it's a clone of google static maps but you can send any amount of data to it. https://github.com/jperelli/osm-static-maps
使用 osm-static-maps,它是谷歌静态地图的克隆,但您可以向它发送任意数量的数据。https://github.com/jperelli/osm-static-maps
Disclaimer: I'm the author.
免责声明:我是作者。

