0

I recently developed a dealer geolocation platform with Google Maps V3 Js API, however I realized that when the user enters a zip code, geolocation is poor.

For example, if the user searches 13001 (1st district of Marseilles), geolocation is done on Aix-en-Provence (whose INSEE code is 13001). Ditto for 13007 (7th arrondissement of Marseille), returns Auriol 20km from Marseille.

It seems that this is the following piece of code that returns the wrong coordinates :

function GoogleGeocode(){
    geocoder = new google.maps.Geocoder();
    this.geocode = function(address, callbackFunction) {
        geocoder.geocode( { 'address': address}, function(results, status) {
          if (status === google.maps.GeocoderStatus.OK) {
            var result = {};
            result.latitude = results[0].geometry.location.lat();
            result.longitude = results[0].geometry.location.lng();                        
            callbackFunction(result);
          } else {
            if (settings.geocodeErrorAlert != "") {
              alert(settings.geocodeErrorAlert + status);
            }
            callbackFunction(null);
          }
        });
    };
  }

Do you have an explanation and a solution to solve this problem?

Thank you all

DevFdbck
  • 51
  • 1
  • 2

1 Answers1

0

I've got the same problem and I managed to solve it by passing the digits in the search string to an additionnal parameter of the geocoder.

    var rawAddress = jQuery('#postcode').val();
    var components = {};

    // Test if the address only contains digits
    if(/^\d+$/.test(rawAddress)){
        components.postalCode = address;
    }
    var geocoder = new google.maps.Geocoder();
        geocoder.geocode({address: address, componentRestrictions: components}, geocoderCallback);

In this example, the postal code is correctly sent, only if the search doesn't contain anything else.

If you want to use a postal code which is in a more complex search string, you'll need to extract the substring of digits from it like this:

var rawAddress = jQuery('#postcode').val();
var digits = rawAddress.match(/\d+/g);

if(digits != null && digits.length > 0){
            for(var i = 0 ; i < digits.length ; i++){
                if(digits[i].length == 5){
                    components.postalCode = digits[i];
                    address = address.replace(digits[i], '');
                }
            }
        }
Flinth
  • 487
  • 2
  • 9