Search code examples
javascriptgoogle-mapsgoogle-maps-api-3postal-code

Google Maps API and Google Maps location shows different location in PHP


I am integrating my client website with Google APIs, and I have a task to validate the user address by using the user's postcode (UK), and to get the address, I have used https://ideal-postcodes.co.uk/.

So, when a user enter a postcode, then an ajax request is sent to this postcode URL with the postcode the user entered. And it returns a set of addresses from that postcode, and the user selects one of them.

Now, this postcode URL also returns the lat and long for that particular postcode. And for the next step, I have used the Google Maps API, which shows direction, distance, and route from source to destination.

That all works fine, but for some postcodes, it shows the wrong location.

When I check that postcode in Google Maps, it shows fine; hence there is no issue with lat & long. There is instead something else which I have been yet unable to find.

Please help me out guys. I have tried searching and using many different ways of coding, but still it remains same.

Here is my JS code, in which I have calculated multiple distances.

var map;
var latc;
var lonc;
var latd;
var lond;
var latr;
var lonr;
var directionsService;
var directionsDisplay;
var orgin;
var destinations;
var midway;
var waypoints = [];
var service;
var stat = false;
function initMap()
{
    map = null;
    waypoints=[];
    directionsDisplay = null;
    directionsService = null;
    orgin = "";
    destinations = "";
    latc = $("#lat").val();
    lonc = $("#lon").val();
    latd = $("#latd").val();
    lond = $("#lond").val();
    lonr = $("#lonr").val();
    latr = $("#latr").val();
    orgin = {lat: parseFloat(latc), lng: parseFloat(lonc)};
    if(latr==="0" && lonr==="0")
    {
        destinations = {lat: parseFloat(latd), lng: parseFloat(lond)};
    }
    else
    {
        stat = true;
        waypoints.push({
            location: new google.maps.LatLng(parseFloat(latd),parseFloat(lonr)),
            stopover:true
        });
        midway = {lat: parseFloat(latd), lng: parseFloat(lonr)};
        destinations = {lat: parseFloat(latr), lng: parseFloat(lonr)};
    }
    console.log(orgin);
    console.log(destinations);
    directionsService = new google.maps.DirectionsService;
    directionsDisplay = new google.maps.DirectionsRenderer;
    map = new google.maps.Map(document.getElementById('map'), {
        center: orgin,
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    });
    directionsDisplay.setMap(map);
    calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay)
{
        directionsService.route(
            {
                origin: orgin,
                destination: destinations,
                waypoints: waypoints,
                durationInTraffic: true,
                optimizeWaypoints: true,
                provideRouteAlternatives: true,
                avoidHighways: false,
                avoidTolls: false,
                travelMode: google.maps.TravelMode.DRIVING
            },
            function(response, status)
            {
                if (status === google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(response);
                    distanceandduration();
                }
                else
                {
                    window.alert('Directions request failed due to ' + status);
                }
            }
        );
}
function distanceandduration()
{
    if(latr==="0" && lonr==="0")
    {
        var a = new Array(orgin);
        var b = new Array(destinations);
    }
    else
    {
        var a = new Array(orgin,midway);
        var b = new Array(midway,destinations);
    }
    service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix({
        origins: a,
        destinations: b,
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC,
        durationInTraffic: true,
        avoidHighways: false,
        avoidTolls: false
    }, function (response, status) {
        if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
            var distnumber = [];
            var durationnumber = [];
            var dvDistance = document.getElementById("showde");
            dvDistance.innerHTML = "";
            dvDistance.innerHTML = "<div class='row-fluid'><div class='control-group span12'><div class='controls'>";
            for(var i=0;i<response.rows.length;i++)
            {
                var distance = "";
                var duration = "";
                if(i===0)
                {}else{
                    dvDistance.innerHTML += "<br/>";
                }
                distnumber[i] = Math.round(parseInt(response.rows[i].elements[i].distance.value)/1000);
                durationnumber[i] = rectime(response.rows[i].elements[i].duration.value);
                console.log(response.rows[i].elements[i].duration);
                distance += response.rows[i].elements[i].distance.text;
                duration += response.rows[i].elements[i].duration.text;
                dvDistance.innerHTML += "<h2>Route "+(i+1)+"</h2>";
                dvDistance.innerHTML += "Distance: " + distance + "<br />";
                dvDistance.innerHTML += "Duration:" + duration;
                dvDistance.innerHTML += "<hr>";
            }
            dvDistance.innerHTML +="</div></div></div>";
            if(latr==="0" && lonr==="0")
            {
                enquirydetailreport(distnumber,durationnumber,'oneway');
            }
            else
            {
                enquirydetailreport(distnumber,durationnumber,'return');
            }
        } else {
            alert("Unable to find the distance via road.");
        }
    });
}
function rectime(sec) {
    var hr = Math.floor(sec / 3600);
    var min = Math.floor((sec - (hr * 3600))/60);
    sec -= ((hr * 3600) + (min * 60));
    sec += ''; min += '';
    while (min.length < 2) {min = '0' + min;}
    while (sec.length < 2) {sec = '0' + sec;}
    hr = (hr)?hr:'00';
    return hr+ ':' + min + ':' + sec;
}

And note that this postcode issue occurs only for a few specific postcodes:

Example : Source : CW10 0QF
Waypoint : G78 1EP
Destination : CW10 0QF

Any help is appreciated. Thank you.


Solution

  • Sorry Guys. I got it. I just gave lat and long value wrongly for source and destination. Like Source A has latA and lonA, destination B has latB and lonB. But by mistake i wrote it as Source A latA and lonA, destination B has latb and lonA-> this was my mistake. Hope this helps someone in future. Thank you