18

I have two HTML pages on a site I'm working on. The first page takes in user input (a start and end location) and then passes the info into the Google Maps Javascript API in order to determine the distance between two locations.

User Input for Locations

The second page displays this information for the user.

However, I also have a button called Edit which invokes onclick="window.history.back()".

The problem I'm having is that the two sections for user input also use the Google Autocomplete for addresses, and so when I go to the next page and click the Edit button, the user input is removed from the input box, whereas without Google Autocomplete, it is still maintained in that spot. I'm presuming that the issue lies within the Google Autocomplete itself, but how do I fix this?

Here is the Javascript for Google Autocomplete:

google.maps.event.addDomListener(window, 'load', initialize);
// ==========================================================================================================
// ==========================================================================================================
// ==========================================================================================================
// USES THE GOOGLE PLACES LIBRARY
// ==============================
// This example displays an address form, using the autocomplete feature
// of the Google Places API to help users fill in the information.

var placeSearch, autoCompleteOrigin, autoCompleteDest;
var componentForm = {
  street_number: 'short_name',
  route: 'long_name',
  locality: 'long_name',
  administrative_area_level_1: 'short_name',
  country: 'long_name',
  postal_code: 'short_name'
};

function initialize() {
  // Create the autocomplete object, restricting the search
  // to geographical location types.
  autoCompleteOrigin = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('start')),
        { types: ['geocode'] });
  autoCompleteDest = new google.maps.places.Autocomplete(
      /** @type {HTMLInputElement} */(document.getElementById('destination')),
      { types: ['geocode'] });
  // When the user selects an address from the dropdown,
  // populate the address fields in the form.
  google.maps.event.addListener(autoCompleteOrigin, 'place_changed', function() {
    fillInAddress();
  });
  google.maps.event.addListener(autoCompleteDest, 'place_changed', function() {
    fillInAddress();
  });
}

function fillInAddress() {
  // Get the place details from the autocomplete object.
  var place = autocomplete.getPlace();

  for (var component in componentForm) {
    document.getElementById(component).value = '';
    document.getElementById(component).disabled = false;
  }

  // Get each component of the address from the place details
  // and fill the corresponding field on the form.
  for (var i = 0; i < place.address_components.length; i++) {
    var addressType = place.address_components[i].types[0];
    if (componentForm[addressType]) {
      var val = place.address_components[i][componentForm[addressType]];
      document.getElementById(addressType).value = val;
    }
  }
}

// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(function(position) {
      var geolocation = new google.maps.LatLng(
          position.coords.latitude, position.coords.longitude);
      var circle = new google.maps.Circle({
        center: geolocation,
        radius: position.coords.accuracy
      });
      autocomplete.setBounds(circle.getBounds());
    });
  }
}
freddiev4
  • 2,501
  • 2
  • 26
  • 46

5 Answers5

1

you would have to have a system to store/update/restore form data. one way of doing this is to have generic change and input handlers that save the state into localStorage, and then restore it back on page load (or any other handler you may have)

Here is a fiddle showing a simple way of doing this: http://jsfiddle.net/wnbcsrsL/

You would need to do some namespacing based on the page you're on to avoid name collision (and you also need to make sure that every input has a name) but other than that it's straightforward

Stefan
  • 3,962
  • 4
  • 34
  • 39
1

I solved this by removing the autocomplete="off" attribute before submit. If you already remove it after the initialization, the built-in autocomplete from the browser (tested on Chrome) overwrites the google places autocomplete list. This preserves the intended behaviour from Google and also the input values on browser navigation.

jQuery solution:

$('input[type="submit"]').click(function () {   
    $('input[autocomplete="off"]').removeAttr('autocomplete');
}
w.stoettinger
  • 1,066
  • 11
  • 11
0

Can you modify the given Google Autocomplete JS? or is that restricted, vendor code?

If so, I'd be eager to try removing this line:

document.getElementById(component).value = '';

I don't think this has anything to do with your use of History. You can confirm that by checking whether the behavior of your edit button is different from the browser Back button.

Reed Spool
  • 843
  • 7
  • 15
  • I tried removing that line, and it had no effect on what the addresses; they didn't save if I went back to the page. – freddiev4 Sep 01 '15 at 23:35
-1

To maintain the values in the edittext field when the page reloads, you need to make use of the various local storage mechanism that are supported by the browsers. Some of them are as follows:

  • File API
  • IndexedDB
  • Web Storage
  • Cookies

For this particular scenarios I would make use of the Web Storage where you would have a persistent session based storage. The data in the edittext field will persist till the user close the browser completely.

Here is a code sample implementation:

window.onbeforeunload = function() {
    localStorage.setItem(addresss1, $('#addresss1').val());
    localStorage.setItem(addresss2, $('#addresss2').val());

}

This is a syncronous call, so whenever the user switch back to this page you can check to see if the data is still there. Follow this code sample.

window.onload = function() {

    var name = localStorage.getItem(address1);
    if (name !== null) $('#address1').val(address1);

    // ...
}

getItem returns null if the data does not exist.

AniV
  • 3,997
  • 1
  • 12
  • 17
  • 1
    If you are recommending session based storage, it should be sessionStorage.setItem and sessionStorage.getItem. localStorage will hold the data indefinitely, beyond the end of the browser session. – GuyH May 28 '15 at 00:54
  • Hi. So I've followed the code implementation of this and the sessions don't seem to be working. All I see when I hit the `Edit` button and `window.history.back()` is invoked, is `[object Object]`, which I'm assuming is the indication that it's returning `null` – freddiev4 May 29 '15 at 20:39
  • 1
    Although this will indeed work for a page refresh I am quite certain the `load` event is not fired on page navigation. – David Mulder Jun 03 '15 at 09:25
  • @FreddieV4 [object Object] is the result of sending an object to a text-based storage. (.toString()) You need to stringify the value before saving it JSON.stringify($('#addresss1').val()); and then parse it back to json when you read it. Alternatively, you can try something like http://garlicjs.org/ – NodeNodeNode Oct 07 '15 at 20:31
-1

instead of window.history.back() you could also pass parameters from webpage 2 to webpage 1 (and vice-versa) by parameters in the url.

here you can see how to pass parameters with javascrip: How to get the value from the GET parameters?

So on your second webpage replace the

window.history.back()

to

window.location=http://mywebpage1.bla?param1=something&param2=something

In your first page in the onload of the page you can check to see if there are parameters present and set the values of the input fields

grtz,S.

Community
  • 1
  • 1
4nti
  • 196
  • 1
  • 14
  • In the `onload` of the page, there is a function called `initialize()` which adds the user input to the URL on the next page as parameters. Example: `?start=125+High+Street%2C+High+Street%2C+Boston%2C+MA%2C+United+States&dest=Ontario%2C+Canada` – freddiev4 Jun 09 '15 at 01:51