Search code examples
javascriptgoogle-mapsgoogle-geocoder

Update google map from postcode on page load


I'm trying to generate a map on page load from a postcode value.

To do this I'm geocoding the dynamic postcode that is given and I have got it to give me a longitude and latitude from that dynamic postcode.

The postcode is sent from a form on a previous page and is stored in the url like so:

url.com?postcode=XXXXXX

The problem now is how do I join up the longitude and latitude values to pass through into the following:

center: new google.maps.LatLng(longitude, latitude)

This is the JS I have at the moment:

var postcodeValue = $('#map').attr('data-postcode');
  function latLong(location, callback) {
  var geocoder = new google.maps.Geocoder();
  var address = location;
  var longitude;
  var latitude;
  geocoder.geocode({
    'address': address
  }, function (results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      latitude = results[0].geometry.location.lat();
      longitude = results[0].geometry.location.lng();
      callback(latitude, longitude);
    }
  });
}

latLong(postcodeValue, function(lat, lon) {
  console.log(lat);
  console.log(lon);
});

var options = {
  mapTypeControlOptions: {
    mapTypeIds: [ 'Styled']
  },
  center: new google.maps.LatLng(latLong),
  zoom: 12,
  mapTypeId: 'Styled',
  disableDefaultUI: true,
  draggable: false,
  disableDoubleClickZoom: true
};

var div = document.getElementById('map');
var map = new google.maps.Map(div, options);
var styledMapType = new google.maps.StyledMapType(styles);

map.mapTypes.set('Styled', styledMapType);

Anyone able to help with this please?


Solution

  • What you can do, is read the hash. Example: mywebsite.com#9000 . Any thing to the right of the hash is ideal to be used as variables for javascript.

    I added some links to 3 Belgian cities. href="?1#1000" , href="?2#8000". Notice: the "?1" and "?2" are just added to make sure the URL is different (left of the #), otherwise the web browser won't change the page.

    I disabled a few of your lines of code regarding the map style. Feel free to add the back.

    Look at line 9 to change the country.

    <html>
    <head>
      <title>Update google map from postcode on page load</title>
      <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
      <script>
      function initialize() {
        // read the hash in the url
        var postcodeValue = window.location.hash.substring(1) || 1000 ;// example:  mywebsite.com?p=maps#1000  ;  1000 is default, if no postal code is in the url
        postcodeValue += ', BE';  // probably best to add a country
    
        var div = document.getElementById('map');
        var map;
    
        latLong(postcodeValue, function(lat, lon) {
          var options = {
            mapTypeControlOptions: {
              // mapTypeIds: [ 'Styled']
            },
            center: new google.maps.LatLng(lat, lon),
            zoom: 12,
            // mapTypeId: 'Styled',
            disableDefaultUI: true,
            draggable: false,
            disableDoubleClickZoom: true
          };
          map = new google.maps.Map(div, options);
        });
    
        // var styledMapType = new google.maps.StyledMapType(styles);
        // map.mapTypes.set('Styled', styledMapType);
    
        function latLong(location, callback) {
          var geocoder = new google.maps.Geocoder();
          var address = location;
          var longitude;
          var latitude;
          geocoder.geocode({
            'address': address
          }, function (results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
              latitude = results[0].geometry.location.lat();
              longitude = results[0].geometry.location.lng();
              callback(latitude, longitude);
            }
          });
        }
      }
      google.maps.event.addDomListener(window, 'load', initialize);
      </script>
      <style>
        #map {
          height: 400px;
        }
      </style>
    </head>
    <body>
      <a href="?1#1000">Brussels</a>
      <a href="?2#8000">Bruges</a>
      <a href="?3#9000">Ghent</a>
      <div id="map">
    </body>
    </html>