Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Position of Mouse Cursor on Mouseover of Google Maps V3 API Marker

I am trying to make a div visible at the position of the cursor when the cursor mouseover a marker using jQuery. Its kind of like a tooltip. However I cannot seem to figure out how to get the X/Y coordinates of the point below the cursor.

Current Code:

google.maps.event.addListener(marker, "mouseover", function(event) {

    $("#tooltip").css({
        position: "absolute",
        top: event.pageY,
        left: event.pageX
    }).toggle();

I believe event does not have the properties pageY and pageX like in the event in jQuery.

How do I get the position of the mouse cursor?

like image 956
Nyxynyxx Avatar asked Jul 02 '11 16:07

Nyxynyxx


People also ask

How do you get the mouse pointer position?

Once you're in Mouse settings, select Additional mouse options from the links on the right side of the page. In Mouse Properties, on the Pointer Options tab, at the bottom, select Show location of pointer when I press the CTRL key, and then select OK. To see it in action, press CTRL.

How do I move a marker in Google Maps API?

Just try to create the marker and set the draggable property to true . The code will be something as follows: Marker = new google.


2 Answers

This is an extension of my previous answer regarding the computation of the pixel positions (Google maps API v3). Introduce a "global" variable overlay:

var overlay = new google.maps.OverlayView();
overlay.draw = function() {};
overlay.setMap(map); // 'map' is new google.maps.Map(...)

Use overlay in the listener to get the projection and the pixel coordinates:

google.maps.event.addListener(marker, 'mouseover', function() {
    var projection = overlay.getProjection(); 
    var pixel = projection.fromLatLngToContainerPixel(marker.getPosition());
    // use pixel.x, pixel.y ... (after some rounding)
}); 

You may also have a look at projection.fromLatLngToDivPixel().

like image 157
Jiri Kriz Avatar answered Oct 04 '22 11:10

Jiri Kriz


Here's a solution that uses the MouseEvent of the click event but does not rely on accessing that via an undocumented property that can change at any time like 'ub' or 'wb' (I think it's 'ya' currently).

map.data.addListener('mouseover', function (e) {
    var keys = Object.keys(e);
    var x, y;
    for (var i = 0; i < keys.length; i++) {
        if (MouseEvent.prototype.isPrototypeOf(e[keys[i]])) {
            x = e[keys[i]].clientX;
            y = e[keys[i]].clientY;
        }
    }
});
like image 32
zeke Avatar answered Oct 04 '22 11:10

zeke