计算地图多边形宽度和高度

时间:2014-04-24 07:48:52

标签: javascript jquery

我们说我有这张地图:

<map name="diffmap1" id="diffmap1" class="myMap">
<area shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

和jquery:

$('.diff').click(function(e){
//code here
});

如何计算每个多边形的最大高度和宽度?

1 个答案:

答案 0 :(得分:1)

以下是HTML代码:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<img src="planets.gif" width="145" height="126" alt="Planets" usemap="#diffmap1">
<map name="diffmap1" id="diffmap1" class="myMap">
<area id="area1" shape="poly" coords="152,347,253,292,264,307,167,358" class="diff diff1">
<area id="area2" shape="poly" coords="93,244,164,215,171,233,97,264" class="diff diff2">
</map>

和JS代码:

function getDistance(p1,p2){
    return Math.sqrt((p2.y - p1.y)*(p2.y - p1.y) + (p2.x - p1.x)*(p2.x - p1.x));
}
$(document).ready(function(){
    var area_distances_min_max = new Object();
    $.each($('area'), function(){
        var arr_coords = $(this).attr('coords').split(',');
        var i = 0;
        var k = 0;
        var arr_real_coords = new Array();
        while(i<arr_coords.length){
            var obj = new Object();
            obj.x = arr_coords[i];
            obj.y = arr_coords[++i];
            arr_real_coords.push(obj);
            i++;
            k++;
        }

        var arr_distances = new Array();
        $.each(arr_real_coords, function(){
            var current_coord = this;
            $.each(arr_real_coords, function(){
                if(getDistance(current_coord,this)>0)arr_distances.push(getDistance(current_coord,this))
            })
        })

        var obj = new Object();

        obj.max = Math.max.apply(Math,arr_distances); 
        obj.min = Math.min.apply(Math,arr_distances);


        var id = $(this).attr('id')
        area_distances_min_max[id] = obj;
    })
    console.log(area_distances_min_max);
})

在数组中,area_distances_min_max将存储点之间的最小和最大距离,您也可以在控制台中查看结果:http://jsfiddle.net/aaa_borza/eer8k/18/

祝你好运!