简体   繁体   中英

Google Maps API using jQuery Plugin: How to get a marker's latitude and longitude on click?

I am using a plugin for Google Maps API V3. I use it to put a marker on the map and allow the user to drag the marker to a spot on the map. I want to get the lat,lng of the marker on click.

goMap Plugin Page: http://www.pittss.lv/jquery/gomap/index.php

This function that sets up the marker in the first place.

$("#map").goMap({ 
   zoom: 16,
   maptype: 'ROADMAP',
   navigationControl: false, 
   mapTypeControl: false, 
   scrollwheel: true, 
   disableDoubleClickZoom: false,
   markers: [{  
       draggable:true,
       latitude: data.lat, 
       longitude: data.lng, 
       icon:'./images/pink.png'
  }] 
});           

I tried calling the native getLat() method on goMap(), but I don't think I was doing that right. Any help is much appreciated.

After a bit of sleuthing, it looks like it uses jQuery's data() function to bind data to the map. You can get to the data through $('#map').data() , which has information on markers.

Each marker has an id, and you can get the marker's id through the array $.goMap.markers . Note that $.goMap.markers only contains strings that are IDs and not the markers themselves.

You'll need to use that array to find the id you want (or you might know it ahead of time) and then call $('#map').data()['MARKER_ID'] to get the marker object. The marker has a few properties, including title , visible , icon , id , and position .

We care about position , which has two properties, wa and ya . wa seems to be latitude, while ya seems to be longitude. So $('#map').data()['MARKER_ID'].position.wa will get you the latitude, for example. It seems some markers have a latitude and longitude property, not sure why that's not always there (from my brief testing at least), but you could try $('#map').data()['MARKER_ID'].latitude instead.

Hope this helps.

I don't know why, but the props names changing often with the time... Seems like the best solution is get the key names and use to know the lat & lng.

So, if you want to get the coords after a drag, for example, you'll use:

$.goMap.createListener({type:'marker', marker:'MARKER_ID'}, 'dragend', function() {

    var i_prop = 2;
    var map_data_marker = $('#map').data()['MARKER_ID'].position;
    var map_data_marker_keys = [];

    for (var key in map_data_marker)
    {
        if (i_prop--)
        {
            if (map_data_marker.hasOwnProperty(key))
            {
                map_data_marker_keys.push(key);
            }
        }
        else
        {
            break;
        }
    }

    var lat_lng = map_data_marker[map_data_marker_keys[0]] + ', ' + map_data_marker[map_data_marker_keys[1]];

}); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM