将地图视窗点击位置转换为地图坐标(Bing地图)

Convert map viewport click position to map coordinates (Bing maps)

本文关键字:地图 坐标 Bing 转换 位置      更新时间:2023-09-26

所以我有一个canvas覆盖在Bing JavaScript v7地图上,这个想法是,当用户点击画布时,它在地图后面的同一点创建一个图钉。

然而,在我目前拼凑的代码中,总是把图钉放在错误的地方。小提琴作为参考;http://jsfiddle.net/89SCq/2/

我如何修正数学使其工作?注意:我必须使用一个覆盖的画布,而不是直接在地图上捕获点击事件。

好的,如果您必须使用画布,您可以计算用户在画布上单击的像素坐标,然后通过相对于地图控件位置的tryPixelToLocation方法传递这些坐标。这是点击事件的更新版本:

$("canvas").click(function(e){
    var relativeX = e.pageX - this.offsetLeft;
    var relativeY = e.pageY - this.offsetTop;
    var loc = map.tryPixelToLocation(new Microsoft.Maps.Point(relativeX, relativeY), Microsoft.Maps.PixelReference.control);
    // push pin; location is top right corner in degs plus a portion of map degree dimension based on relative click pos
    map.entities.push(
        new Microsoft.Maps.Pushpin(loc, null)
    );
    // DEBUG; zoom out to show marker pos
    map.setView({ zoom: 9 });    
});

为什么要使用画布?为什么不像这样在地图中添加一个点击事件呢?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
  <title></title>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
  <script type="text/javascript" src="http://ecn.dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=7.0"></script>
  <script type="text/javascript">
    var map;
    function GetMap()
    {   
        map = new Microsoft.Maps.Map(document.getElementById("myMap"), { 
            credentials: "YOUR_BING_MAPS_KEY"
        });
        Microsoft.Maps.Events.addHandler(map, 'click', addPushpin);
    }
    function addPushpin(e){
        var loc = map.tryPixelToLocation(new Microsoft.Maps.Point(e.getX(), e.getY()));
        var pin = new Microsoft.Maps.Pushpin(loc);
        map.entities.push(pin);
    }
    </script>
</head>
<body onload="GetMap();">
    <div id='myMap' style='position:relative;width:800px;height:600px;'></div>
</body>
</html>