Add marker to Google Map on site, use javascript variables in PHP Processor

I have the following code to place 2 maps onto a web page, and then allow live updating of each as a new address is input into the text field. What I would like to do now, is when the map is updated, add a Google Maps Marker to the view (I have some code I was attempting to use but it wasn’t placing the marker). Once this is utilized (in my end product) I would like to retrieve some of the javascript variables (namely toAddressLat, toAddressLng, fromAddressLat, and fromAddressLng) in my PHP form process so I can include them in the compiled email to the website admins.

Hope I have explained that clearly enough, any assistance anyone can offer would be greatly appreciated for either of these steps.

Greg

CODE INCLUDED BELOW:


<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>Show 2 Google Maps</title>
  <meta name="description" content="Google Dual Maps">
  <meta name="author" content="Greg Hicks">
  <link rel="stylesheet" href="twomaps.css?v=1.0">
<!-- Call Google Maps API -->
<script type="text/javascript" src="https://maps.google.com/maps/api/js?key=MyGoogleMapsKeyUseYourOwn(-:&sensor=true"></script>
<script>
/** Start Building our FROM Map **/
  var frommap;
  fromgeocoder = new google.maps.Geocoder();
  function initializefrom() {
    var frommapOptions = {
      zoom: 16,
      center: new google.maps.LatLng(34.5400, -112.4678),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    frommap = new google.maps.Map(document.getElementById('from-map-canvas'), frommapOptions);
  } /* function initializefrom */
  function codeFromAddress() {
    var fromaddress = document.getElementById("fromaddress").value;
    fromgeocoder.geocode( { 'address': fromaddress}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var fromAddressLat = results[0].geometry.location.lat();
        var fromAddressLng = results[0].geometry.location.lng();
        var frommypanPoint = new google.maps.LatLng(fromAddressLat, fromAddressLng);
        frommap.panTo(frommypanPoint);
      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  } /* function codeFromAddress */
  google.maps.event.addDomListener(window, 'load', initializefrom);
/** Finished Building our FROM Map **/
/** Start Building our TO Map **/
  var tomap;
  togeocoder = new google.maps.Geocoder();
  function initializeto() {
    var tomapOptions = {
      zoom: 16,
      center: new google.maps.LatLng(34.5400, -112.4678),
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    tomap = new google.maps.Map(document.getElementById('to-map-canvas'), tomapOptions);
  } /* function initializeto */
  function codeToAddress() {
    var toaddress = document.getElementById("toaddress").value;
    togeocoder.geocode( { 'address': toaddress}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var toAddressLat = results[0].geometry.location.lat(); <!-- I would like to pass this to PHP processor script -->
        var toAddressLng = results[0].geometry.location.lng(); <!-- AND this one -->
        var topanPoint = new google.maps.LatLng(toAddressLat, toAddressLng);
        tomap.panTo(topanPoint);
        // Place the marker - CODE DOES NOT PLACE MARKER!!!
        new google.maps.Marker({
          tomap: mapObject,
          position: (toAddressLat, toAddressLng)
    });

      } else {
        alert("Geocode was not successful for the following reason: " + status);
      }
    });
  } /* function codeToAddress */
  google.maps.event.addDomListener(window, 'load', initializeto);
/** Finished Building our TO Map **/
</script> <!-- End Google Maps API call -->
</head>
<body>
  <div id="map-wrapper">
    <h2>Showing Twin Google Maps with Update Function</h2>
    <fieldset>
      <legend>From Address:</legend>
      <label>Address:</label><input type="text" id="fromaddress" onchange="codeFromAddress()">
      <div id="from-map-canvas"></div>
    </fieldset>
    <fieldset>
      <legend>To Address:</legend>
      <label>Address:</label><input type="text" id="toaddress" onchange="codeToAddress()">
      <div id="to-map-canvas"></div>
    </fieldset>
  </div> <!-- map-wrapper -->
</body>
</html>

Here is the CSS just for reference


#map-wrapper {
  width: 45%;
  float: left;
  margin-left: 2%;
}

#map-wrapper fieldset {
  border: 1px solid #57256a;
  padding: 10px;
  margin: 0;
  color: #57256a;
}

#map-wrapper fieldset legend {
  font-size: 1.2em;
  font-weight: bold;
  text-align: left;
  padding-top: 10px;
}

#from-map-canvas {
  width: 100%;
  height: 300px;
  float: left;
}
#to-map-canvas {
  width: 100%;
  height: 300px;
  float: left;
}

OK, got the markers working. I added the following function:

]CODE]
/** Start of Global Functions for both maps /
function addMarker(location, onmap) {
marker = new google.maps.Marker({
position: location,
map: onmap
})
};
/
End of Global Functions for both maps **/



And then by calling it inside of my codeToAddress (or codeFromAddress which I also need to rewrite to use a single function for both maps)

addMarker(topanPoint, tomap); //(or frompanPoint, frommap for the FROM map call)



I placed that just before my tomap.panTo call and now markers are placed (though if the user does more than a single address multiple markers are placed so I may need to create something to clear old markers, but that seems quite cumbersome in the V3 API reference versus how it was done in V2

Greg

Hi Greg,

To answer the second part of your question about sending the lat/lng values to a php script, you could add a couple of hidden fields to your form:


<input type="hidden" id="form_latitude" name="latitude">
<input type="hidden" id="form_longitude" name="longitude">

and update them from your JS:

document.getElementById('form_latitude').value = toAddressLat;
document.getElementById('form_longitude').value = toAddressLng;

When the form is submitted, you can access these variables from $_POST or $_GET as normal.

Hmm, I put those values in but never seem to get the values passed to the form’s hidden fields. Should they show up in a “view source”, or are they only accessible then through POST or GET? I’ve tried both and always end up with blank values.

I have this in my form: <input type=“hidden” name=“fromlatlng” value=“” />
And then I inserted this into my javascript function (the one that updates the map view when an address is typed in)
document.getElementByName(‘fromlatlng’).value = frompanPoint;

Here is all the code for that function:


  function codeFromAddress() {
    var fromaddress = document.getElementById("fromaddress").value;
    fromgeocoder.geocode( { 'address': fromaddress}, function(results, status) {
      if (status == google.maps.GeocoderStatus.OK) {
        var fromAddressLat = results[0].geometry.location.lat();
        var fromAddressLng = results[0].geometry.location.lng();
        var frompanPoint = new google.maps.LatLng(fromAddressLat, fromAddressLng);
        addMarker(frompanPoint, frommap);
        frommap.panTo(frompanPoint);
        document.getElementByName('fromlatlng').value = frompanPoint;
      } else {
        // TODO: Gracefully error on invalid address
        //alert("Geocode was not successful for the following reason: " + status);
      }

Your variable frompanPoint is actually a JS object, which is why you end up with a blank value when you assign it to the hidden form input.

If you want to send the lat/lng as one value instead of two, you could always call .toString(), like this:

document.getElementByName('fromlatlng').value = frompanPoint.toString();

I’ve not tested this, but according to the google map docs, it should give you what you want.