Calculating Google map's viewport?

和自甴很熟 提交于 2019-12-11 14:38:50

问题


I'm doing a bit of geocoding using Google Local Search and need to be able to set the viewport of a google maps api v3 object on the page.

Now this is fine if google local search has returned me a good viewport as it does for a postcode or street but if i put in the name of a bar for example. The viewport returned is very large presumable because local search has found many matches but has returned the best.

I'd like to calculate my own viewport in this case and am doing so in the following manner:

result.Centre = new LatLon(double.Parse(lat),double.Parse(lon));
result.Span = new LatLon(0.006295d, 0.008407d);
string viewport = "{{\"center\":{{\"lat\":\"{0}\",\"lng\":\"{1}\"}},\"span\":{{\"lat\":\"{2}\",\"lng\":\"{3}\"}},\"sw\":{{\"lat\":\"{4}\",\"lng\":\"{5}\"}},\"ne\":{{\"lat\":\"{6}\",\"lng\":\"{7}\"}}}}";
//Calculate the south west by taking half the span and adding it to the centre
double swLat = result.Centre.Latitude + (result.Span.Latitude/2);
double swLon = result.Centre.Longitude + (result.Span.Longitude/2);
//and northeast corners by taking half the span and subtracting from the centre
double neLat = result.Centre.Latitude - (result.Span.Latitude/2);
double neLon = result.Centre.Longitude - (result.Span.Longitude/2);


//Fingers crossed :)
result.ViewPortJSON = string.Format(viewport, result.Centre.Latitude, result.Centre.Longitude,result.Span.Latitude, result.Span.Longitude, swLat, swLon,neLat, neLon);

The problem is I get some valid json but google maps zooms right out so I can see the whole world. The same code is being used at the front end as if google has given me the viewport so I don't understand what is going on.

Any ideas? Have I got my calculations wrong? I have tried with the whole span (i.e. assuming it is already a radius) with the same effect.

Thanks in advance.


回答1:


hey, shouldn't you be doing:

double swLat = result.Centre.Latitude - (result.Span.Latitude/2); 

double swLon = result.Centre.Longitude - (result.Span.Longitude/2); 

//and northeast corners by taking half the span and subtracting from the centre 

double neLat = result.Centre.Latitude + (result.Span.Latitude/2); 

double neLon = result.Centre.Longitude + (result.Span.Longitude/2);


来源:https://stackoverflow.com/questions/2393531/calculating-google-maps-viewport

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!