The following JavaScript function was taken from http://sg.openrice.com/js/en/sdmap.js
(web page that includes this external JS file: http://sg.openrice.com/singapore/restaurant/advancesearch.htm?mapType=1):
function showAllMarkers(data, options) {
var markerGroups = {};
var getcs = function (lat, lng) {
return '' + Math.round(lat * 32768) + Math.round(lng * 32768);
}
for (var i = 0; i < data.length; i++) {
if (markerList[data[i].id]) continue;
if (!(data[i].lat == 0 && data[i]['long'] == 0)) {
var xy = getcs(data[i].lat, data[i]['long']);
if (markerGroups[xy]) {
markerGroups[xy].push(data[i]);
} else {
markerGroups[xy] = [data[i]];
}
}
}
for (var i in markerGroups) {
updateGroupMarker(markerGroups[i], options);
}
}
After the script runs, the function is used to cluster overlapped markers. I totally understand the javascript syntax, but I don’t understand what this line does:
return '' + Math.round(lat * 32768) + Math.round(lng * 32768);
Is there any special purpose for multiplying by 32768? Can anyone explain to me?
Thanks!
That line is just some way of generating a string index (“hash”) for the array markerGroups. What you should learn from it is that “getcs” is an undescriptive name, it makes source code reading harder and you should give functions clearer names that make the meaning clear.
Anyway: The rounding cuts away some digits. Since the author probably does not want to cut away to many digits he has to multiply lat/long with a large enough value to reduce the effect. It looks like 32768 is a more or less random choice (it is 2^15, seems still random).
Ok, now to the collisions: Two coordinates that are very close to each other… Say 0.000001,0.000001 and 0.000002,0.000002 will cause the same hash to be generated. The author then uses these hashes to group all markers that have the same hash.
This is a very simplistic algorithm. It accepts that if you have two markers that are literally right next to each other (like a millimeter distance between them), but it is just at the border where the hash value would change, the algorithm will not group them.
In more illustrative words: The algorithm lays a grid over your map, each cell of the grid having the size 1°/32768 * 1°/32768 (that is approximately up to 3,4*3,4 meters per square on the equator, 3,4m * 2,2m in Germany/at the border between USA/Canada if the coordinate system is WGS84. The size of the square will vary a lot depending on position on earth) and every marker within one grid cell gets the same hash value and is consequently grouped together.