This ibge site that you passed serves us well, we will do a reverse engineering on it to discover the polygons!
We can start understanding how this map is rendered on their website, so we can use Chrome’s Veloper tools and inspect the element that contains the map to understand where it comes from:
The map comes from an iframe, interesting, we will follow this link:
That is the result:
Let’s inspect the source code and try to find the code that adds this Shape on google maps:
A-ha! From there we can find the web service that it accesses to get the data from Shape:
var codigo = jsget['codigo'];//33';//3303302';
var idnivel = jsget['idnivel'];//'MU';
var fcomp = jsget['fcomp'];//'100';//1000';
var urlServicoMapas = "shapes/" + codigo.substr(0, 2) + "/" + idnivel + "_M13_" + codigo + "_" + fcomp + ".json";
From there we deduce that the url in this case is:
http://www.cidades.ibge.gov.br/gmap/shapes/35/MU_M13_3550308_1000.json
If you access this url, you will see that Shape is truncated in some format, but it is no problem, continuing to read the source code, we can see that it uses a "compactor", which is in another url:
<script language="javascript" src="compactador.js"></script>
That’s the code we’re interested in:
function descompacta(string) {
var myArray = [];
var str, str2, arr, arr2, lat, lng, f;
var strings = string.split(" ");
for (var i in strings)
{
str = strings[i];
str2 = '';
arr = [];
arr2 = [];
for (var j=0; j<str.length; j++)
{
switch (str.charAt(j))
{
case 'A': str2 += ',0'; break;
case 'B': str2 += ',1'; break;
case 'C': str2 += ',-1'; break;
case 'D': str2 += ',2'; break;
case 'E': str2 += ',-2'; break;
case 'F': str2 += ',3'; break;
case 'G': str2 += ',-3'; break;
case 'H': str2 += ',4'; break;
case 'I': str2 += ',-4'; break;
case 'J': str2 += ',5'; break;
case 'K': str2 += ',-5'; break;
case 'L': str2 += ',6'; break;
case 'M': str2 += ',-6'; break;
case 'N': str2 += ',7'; break;
case 'O': str2 += ',-7'; break;
case 'P': str2 += ',8'; break;
case 'Q': str2 += ',-8'; break;
case 'R': str2 += ',9'; break;
case 'S': str2 += ',-9'; break;
default: str2 += str.charAt(j); break;
}
}
arr = str2.split(",");
f = arr.shift();
lng = parseInt(arr[0])/f;
lat = parseInt(arr[1])/f;
arr2.push([lat, lng]);
for (var j=2; j<arr.length; j+=2)
{
lng += parseInt(arr[j])/f;
lat += parseInt(arr[j+1])/f;
arr2.push([lat, lng]);
}
myArray.push(arr2);
}
return myArray;
}
Running the webservice result in this function, we get an array with our Shape:
http://pastebin.com/C7bVwNct
Here, for example, has the code of the municipalities https://github.com/waltercruz/estados-municipios-ibge - Obviously there must be a place to download the official data, but the IBGE site is full of broken links, I will not search now :P.
– Bacco
Thank you so much for helping @Andréabadesso.
– Rodolfo Oliveira