Search code examples
javascriptphpajaxmaps

Trigger PHP function request when Google Maps marker is moved


When a marker is placed, I want to call a PHP function (in another file) with the latitude and longitude as input and output the result in a div on the page. So whenever the marker is moved, it updates the div with the latest result of the function.

I know I'd need JavaScript to do this but I'm not very familiar with it and any help would be appreciated.


Solution

  • Here is an example using jQuery to trigger a HTTP GET when a marker is added to the map and whenever it is dragged. The result of the request is placed in a div with id "outputdiv".

    // create and init map (make sure to have a div element with id "map")
    var map = new GMap2(document.getElementById("map"));
    map.setCenter(new GLatLng(37.4419, -122.1419), 13);
    
    // this is the marker you want to track
    var marker = new GMarker(new GLatLng(37.4419, -122.1419));
    map.addOverlay(marker);
    
    // create function to be executed on add/end of drag
    var changeCallback = function(latlng) {
      // do HTTP GET to execute PHP function in file, with coordinate
      // as parameter and put result in div with id "outputdiv"
      $("#outputdiv").load("test.php?latlng=" + latlng.toUrlValue());
    };
    
    // add listener triggered whenever drag of marker has ended
    GEvent.addListener(marker, "dragend", changeCallback);
    
    // explicitly call when added
    changeCallback(marker.getLatLng());
    

    Update to answer comment: The latlng parameter of the callback function is a GLatLng object where you may use lat() and lng() to retrieve the individual values. See Google Maps API reference for details.