javascript - 谷歌地图 - 将光标更改为图像拾取偏移

标签 javascript css google-maps google-maps-api-3 mouse-cursor

我已将谷歌地图光标更改为我自己的图像。该图像具有一定的独特意义。该网站允许人们点击 map 上的某处,以在他们选择的确切纬度/经度处创建标记。

问题是因为图像有一个特定的点(图像的底部中心),所以每个人都认为那个点在哪里,标记就会去哪里。相反,标记位于图像的左上角,并且偏离了相当多的像素。

我需要的是一种偏移图像的方法,这样当点击发生时,它恰好发生在图像点所在的位置,而不是自动选择的位于左上角的点。

我试图在 photoshop 中使图像本身偏离中心,但没有成功。我查看了 google maps api,但没有弹出任何内容。

关于如何实现这一点有什么想法吗?

最佳答案

您可以在 https://developers.google.com/maps/documentation/javascript/maptypes#PixelCoordinates 找到实现它的基本公式

pixelCoordinate = worldCoordinate * 2zoomLevel

Get the worldCoordinate of the click, calculate the pixelCoordinate, add the offset , calculate the new worldCoordinate and you have the desired position.

You'll need two functions to convert LatLng's to Pixel(and vice versa):

fromLatLngToPoint() and fromPointToLatLng()

sample-function:

  google.maps.event.addListener(map, 'click', function(e){      
       //assume a cursor with a size of 22*40

   var  //define the anchor, the base(top-left) is 0,0
        //bottom middle will be 11,40
       anchor         = new google.maps.Point(11,40),

        //the map-projection, needed to calculate the desired LatLng
       proj           = this.getProjection(),

        //clicked latLng
       pos            = e.latLng;

        //the power of the map-zoom
       power          = Math.pow(2,map.getZoom()),

        //get the world-coordinate
        //will be equal to the pixel-coordinate at zoom 0
       point          = proj.fromLatLngToPoint(pos),

        //calculate the new world-coordinate based on the anchor
       offsetPoint    = new google.maps.Point(
                                        (point.x*power+anchor.x)/power,
                                        (point.y*power+anchor.y)/power
                                       ),
        //convert it back to a LatLng
       offsetPosition = proj.fromPointToLatLng(offsetPoint);

       //done

       new google.maps.Marker({ position:offsetPosition, map:map});
  });

演示:http://jsfiddle.net/doktormolle/NYh7g/

关于javascript - 谷歌地图 - 将光标更改为图像拾取偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25072892/

相关文章:

javascript - while 循环必须是无限的才会崩溃吗?

javascript - 比较 Javascript/Angular 中的 2 个 Json 对象

html - CSS类覆盖其他

javascript - 谷歌地图,样式不适用于带类的标记 img,但适用于 img[src]

android - 在 Android 中使用谷歌地图

javascript - 向数组中的对象添加新元素

php - 为什么序列化不包含提交按钮名称?

CSS3 : Is it possible to have thousands separator in numbers?

使用 require js 优化器的 CSS 缩小

javascript - Google Map API 加载动态信息窗口