JavaScript仅检测土地或水谷歌地图

时间:2016-01-28 22:43:42

标签: javascript api google-maps

我很难找到一种只能用JavaScript来检测特定(lat,lng)的土地与水的方法。使用画布工作并绕过Chrome污染的画布错误。以为我提出问题然后回答。

1 个答案:

答案 0 :(得分:0)

function landOrWater( lat, lng, callback ) {
    var map_url = "http://maps.googleapis.com/maps/api/staticmap?center="+lat+","+lng+"&zoom="+map.getZoom()+"&size=1x1&maptype=roadmap"
    var canvas = document.createElement('canvas');
    var ctx = canvas.getContext('2d');

    var image = new Image();
    image.crossOrigin = "Anonymous"; // dope hack
    image.src = map_url;

    image.onload = function() {
        canvas.width = image.width;
        canvas.height = image.height;
        canvas.getContext('2d').drawImage(image, 0, 0, image.width, image.height);
        var pixelData = canvas.getContext('2d').getImageData(0, 0, 1, 1).data;
        if( pixelData[0] > 160 && pixelData[0] < 181 && pixelData[1] > 190 && pixelData[1] < 210 ) {
            result = "water";
        } else {
            result = "land";
        }
        callback(result);
    }
}

landOrWater( somelat, somelong, function(result){
    console.log( result );
});