如何访问 Google Maps API v3 标记的 DIV 及其像素位置? [英] How to access Google Maps API v3 marker's DIV and its pixel position?

查看:16
本文介绍了如何访问 Google Maps API v3 标记的 DIV 及其像素位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在标记上使用其他 jQuery 工具提示插件,而不是 Google Maps API 的默认信息窗口.所以我需要获取标记的 DIV 及其像素位置.

Instead of Google Maps API's default info window, I'm going to use other jQuery tooltip plugin over marker. So I need to get marker's DIV and its pixel position.

但无法获取,因为某些标记没有 id 或 class.只有我可以从标记对象和未记录的 pixelBounds 对象访问地图画布 div.

But couldn't get it because there are no id or class for certain marker. Only I can access map canvas div from marker object and undocumented pixelBounds object.

  1. 如何访问标记的 DIV?
  2. 在哪里可以获得 DIV 的像素位置?我可以将经纬度位置转换为像素值吗?

==附加:

我也试过下面的代码,但是当我滚动地图时它没有改变.

I also tried with below code, but it doesn't change when I scroll the map.

var marker = new google.maps.Marker({...});
google.maps.event.addListener(marker, 'click', function() {
    var px = this.getMap().getProjection().fromLatLngToPoint(this.getPosition());
    console.log("(" + px.x + "," + px.y + ")");
});

推荐答案

我真的不明白为什么要为标记获取特定的 div?如果您想显示工具提示,那么您只需要标记锚点的像素位置(以及有关标记大小和锚点位置的知识),而不是 div 元素.当 google.maps 端发生事件时,您始终可以手动触发打开和关闭工具提示.

I don't really get why would you want to get specific div for marker? If you want to display tooltip then all you need is pixel position of markers anchor (and knowledge about size of marker and placement of anchor), not div element. You can always trigger opening and closing tooltip by hand when event occurs on google.maps side.

要获取给定标记的锚点的像素位置,您可以使用以下代码:

For getting pixel position of anchor of given marker you can use this code:

var scale = Math.pow(2, map.getZoom());
var nw = new google.maps.LatLng(
    map.getBounds().getNorthEast().lat(),
    map.getBounds().getSouthWest().lng()
);
var worldCoordinateNW = map.getProjection().fromLatLngToPoint(nw);
var worldCoordinate = map.getProjection().fromLatLngToPoint(marker.getPosition());
var pixelOffset = new google.maps.Point(
    Math.floor((worldCoordinate.x - worldCoordinateNW.x) * scale),
    Math.floor((worldCoordinate.y - worldCoordinateNW.y) * scale)
);

pixelDistance 中,您可以获得从地图左上角开始计算的特定标记锚点的偏移量(您可以从 map.getDiv() div 获得它的位置).为什么它像这样工作(或者有更好的方法?)你可以阅读 谷歌地图叠加文档.

In pixelDistance you get offset of specific marker anchor counted from left upper corner of the map (and you can get it's position from map.getDiv() div). Why it works like this (or is there a better way?) you can read in documentation of google maps overlays.

这篇关于如何访问 Google Maps API v3 标记的 DIV 及其像素位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆