-1

I have two Google map codes. Both have two text boxes which takes addresses and a button. First one calculates and shows the driving distance(doesn't show the map) and the second one shows a navigation line drawn on a Google map between those two addresses. Now when I combine these both codes, none of them works. I guess I am initializing the map twice or there is some conflict being created between these two but I don't now where. So I was wondering if there is any way to make these both work independently or maybe simultaneously. Script tags that I am using:

    <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script>
        <script src="http://maps.google.com/maps?file=api&v=2&key=YOUR_API_KEY" type="text/javascript"></script>
        <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
       <script src="http://www.geocodezip.com/scripts/v3_poly_tooltip.js"></script>

JS code for calculating distance

  var geocoder, location1, location2, gDir;

        function initialize() {
            geocoder = new GClientGeocoder();
            gDir = new GDirections();
            GEvent.addListener(gDir, "load", function() {
                var drivingDistanceMiles = gDir.getDistance().meters / 1609.344;
                var drivingDistanceKilometers = gDir.getDistance().meters / 1000;
                document.getElementById('results').innerHTML = '<strong>Address 1: </strong>' + location1.address + ' (' + location1.lat + ':' + location1.lon + ')<br /><strong>Address 2: </strong>' + location2.address + ' (' + location2.lat + ':' + location2.lon + ')<br /><strong>Driving Distance: </strong>' + drivingDistanceMiles + ' miles (or ' + drivingDistanceKilometers + ' kilometers)';
            });
        }



        function showLocation() {
            geocoder.getLocations(document.forms[0].address1.value, function (response) {
                if (!response || response.Status.code != 200)
                {
                    alert("Sorry, we were unable to geocode the first address");
                }
                else
                {
                    location1 = {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                    geocoder.getLocations(document.forms[0].address2.value, function (response) {
                        if (!response || response.Status.code != 200)
                        {
                            alert("Sorry, we were unable to geocode the second address");
                        }
                        else
                        {
                        location2= {lat: response.Placemark[0].Point.coordinates[1], lon: response.Placemark[0].Point.coordinates[0], address: response.Placemark[0].address};
                        gDir.load('from: ' + location1.address + ' to: ' + location2.address);
                    }
                });
            }
        });
    }

JS for showing navigation line on map:

var HWY431LatLon = new google.maps.LatLng(51.5074,0.1278);
var homeLatLon = HWY431LatLon;
var homeZoom = 13;
var map = null;
var latLngToPixel = null;
var polylineTest = null;


function testMap() {
    var directionsDisplay   = new google.maps.DirectionsRenderer();
    var directionsService = new google.maps.DirectionsService();
    directionsDisplay.setMap(map);
    polylineTest = new google.maps.Polyline({
        path: [],
        strokeColor: '#FF0000',
        strokeWeight: 5
    });
        var start = document.getElementById("start").value;
    var end = document.getElementById("end").value;
    var bounds = new google.maps.LatLngBounds();        
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.TravelMode.DRIVING
    };
    directionsService.route(request, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
            //directionsDisplay.setDirections(response);
            path = response.routes[0].overview_path;
            $(path).each(function(index, item) {
                polylineTest.getPath().push(item);
                bounds.extend(item);
            });
            polylineTest.setMap(map);
            map.fitBounds(bounds);
            google.maps.event.addListener(polylineTest, 'rightclick', function(event) {
                alert("Zooming to the event");
                map.fitBounds(bounds);
            });

            var tooltipOptions={ 
                poly:polylineTest, 
                content:"", 
                cssClass:'tooltip' /* name of a css class to apply to tooltip */
            };

            var tooltip = new Tooltip(tooltipOptions);
            google.maps.event.addListener(polylineTest, "mouseover", function(event) {
                tooltip.setContent(event.latLng.toUrlValue(6));
            });

        }
    });
}


function initGMap(){
    var mapOptions = {
        center: homeLatLon,
        zoom: homeZoom,
        scaleControl: true,
        scaleControlOptions: {
            position: google.maps.ControlPosition.BOTTOM_LEFT
        }
    };
    google.maps.visualRefresh = true;
    map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);

}//function     

$(document).ready(function(){
    initGMap();
});

HTML:

<body onload="initialize()">
    <form action="#" onsubmit="showLocation();testMap(); return false;">
        <p>
            <input type="text" name="address1" id="start" value="Address 1" />
            <input type="text" name="address2" id="end" value="Address 2" />
            <input type="submit" value="Search" onclick="calcRoute()"/>
        </p>
    </form>
    <p id="results"></p>

</body>
Priyank Mehta
  • 2,453
  • 2
  • 21
  • 32
Falak
  • 3
  • 2
  • 1
    can you share the exact error by posting output from the console in developer tools of your browser.. – Priyank Mehta Mar 22 '17 at 07:54
  • You have included the Google Maps API multiple times on this page. This may cause unexpected errors. maps:101:295 The character encoding of the HTML document was not declared. The document will render with garbled text in some browser configurations if the document contains characters from outside the US-ASCII range. The character encoding of the page must be declared in the document or in the transfer protocol. new%201.html – Falak Mar 22 '17 at 08:19
  • jQuery.Deferred exception: a is null _.vg@http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg:87:382 Ag@http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg:89:74 Sb@http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAwk8Uo9ZkiYLo0bvznt5qbxS0fmsgnMxnrcWKglYCnXntU3LFdxT1T4fzWClpC8GEnLS-QqpemIG3fg:178:1247 initGMap@file:///C:/Users/HP/Documents/new%201.html?address1=Address+1&address2=Address+2#:142:11 – Falak Mar 22 '17 at 08:21
  • @file:///C:/Users/HP/Documents/new%201.html?address1=Address+1&address2=Address+2#:147:5 g/ – Falak Mar 22 '17 at 08:21
  • TypeError: b is undefined[Learn More] maps:30:33 TypeError: _.sa is undefined[Learn More] common.js:4:85 "Google Maps API warning: NoApiKeys https://developers.google.com/maps/documentation/javascript/error-messages#no-api-keys" util.js:211:33 TypeError: _.ej is undefined[Learn More] common.js:33:342 – Falak Mar 22 '17 at 08:21
  • I get all these errors in my console – Falak Mar 22 '17 at 08:22
  • Please edit your question to add the errors – geocodezip Mar 22 '17 at 09:49

1 Answers1

3

Okay,

so first you are trying to mix to different version of the API. I suggest you migrate all the code to version 3. Then you don't need to reference twice the API because this is causing error, your <head> should look something like:

   <head>
        <meta charset="UTF-8">
        <link rel="stylesheet" href="style.css">
        <script src="https://maps.googleapis.com/maps/api/js?v=3&key=YOUR_API_KEY"></script>
        <script src="http://code.jquery.com/jquery-3.1.1.min.js"></script>
        <script src="http://www.geocodezip.com/scripts/v3_poly_tooltip.js"></script>
    </head>

Note: sensor parameter is not needed with version 3 of the API

Now about your code - it is awful! I can start to explain why but it will be a long post :)

As I said part of your code is for API version 2 and other for version 3. It will simply start working when you migrate to a single version. Please go and read official google documentation - directions , geocoding

The HTML of the map and form should look something like this:

<form action="#" onsubmit="showLocation(); return false;">
    <p>
        <input type="text" name="address1" id="start" value="Barclays Bank, Heathway" />
        <input type="text" name="address2" id="end" value="Elm Cars" />
        <input type="submit" value="Search"/>
    </p>
</form>
<div id="distance"></div>
<div id="map-canvas" style="width:400px; height:400px;"></div>

And then your script will look something like this:

<script type="text/javascript">

            var
                    homeLatLon = new google.maps.LatLng(51.5074, 0.1278),
                    homeZoom = 13,
                    map,
                    geocoder,
                    latLngToPixel = null,
                    polylineTest = null,
                    directionsDisplay,
                    directionsService;

            function rad(x) {
                return x * Math.PI / 180;
            };

            function showDistance(p1, p2) {
                var R = 6378137; // Earth’s mean radius in meter
                var dLat = rad(p2.lat() - p1.lat());
                var dLong = rad(p2.lng() - p1.lng());
                var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
                Math.sin(dLong / 2) * Math.sin(dLong / 2);
                var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
                var d = R * c;

                document.getElementById('distance').innerHTML = '<strong>Driving Distance: </strong>' + d + ' in meters';
            };

            function showLocation() {
                var address1Location, address2Location;

            geocoder.geocode({'address': document.forms[0].address1.value}, function (results, status) {
                if (status == 'OK') {

                    address1Location = results[0].geometry.location;
                    map.setCenter(address1Location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: address1Location
                    });

                    if (typeof address2Location !== 'undefined') {
                        showDistance(address1Location, address2Location);
                    }

                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });

            geocoder.geocode({'address': document.forms[0].address2.value}, function (results, status) {
                if (status == 'OK') {

                    address2Location = results[0].geometry.location;
                    map.setCenter(address2Location);
                    var marker = new google.maps.Marker({
                        map: map,
                        position: address2Location
                    });

                    if (typeof address1Location !== 'undefined') {
                        showDistance(address1Location, address2Location);
                    }

                } else {
                    alert('Geocode was not successful for the following reason: ' + status);
                }
            });

                directionsService.route({
                    origin: document.getElementById('start').value,
                    destination: document.getElementById('end').value,
                    travelMode: 'DRIVING'
                }, function (response, status) {
                    if (status === 'OK') {
                        directionsDisplay.setDirections(response);
                    } else {
                        window.alert('Directions request failed due to ' + status);
                    }
                });

            }

            function initGMap() {
                var mapOptions = {
                    center: homeLatLon,
                    zoom: homeZoom,
                    scaleControl: true,
                    scaleControlOptions: {
                        position: google.maps.ControlPosition.BOTTOM_LEFT
                    }
                };
                google.maps.visualRefresh = true;
                map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
                geocoder = new google.maps.Geocoder();
                directionsDisplay = new google.maps.DirectionsRenderer();
                directionsService = new google.maps.DirectionsService();
                directionsDisplay.setMap(map);
            }

            $(document).ready(function () {
                initGMap();
            });

 </script>

I won't put any comments or will explain the code to you, so you can at least force yourself to go and read the documentation and try to understand it how it works by yourself.

Good Luck!

E D I T

Okay if you want the distance you need this functions:

function rad(x) {
    return x * Math.PI / 180;
};

function showDistance(p1, p2) {
    var R = 6378137; // Earth’s mean radius in meter
    var dLat = rad(p2.lat() - p1.lat());
    var dLong = rad(p2.lng() - p1.lng());
    var a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
            Math.cos(rad(p1.lat())) * Math.cos(rad(p2.lat())) *
            Math.sin(dLong / 2) * Math.sin(dLong / 2);
    var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
    var d = R * c;

    document.getElementById('distance').innerHTML = '<strong>Driving Distance: </strong>' + d + ' in meters';
};

Refer to the code samples on top how you can call this function.

codtex
  • 6,128
  • 2
  • 17
  • 34
  • Thanks Sand for this solution but it shows the map only not the calculated values – Falak Mar 22 '17 at 09:06
  • I have added

    but it shows nothing
    – Falak Mar 22 '17 at 09:07
  • @Falak just copy paste this code in a blank **HTML** file in the order that it is posted. The code is working perfectly. And please read it and try to understand it `

    ` is actually `
    `. Here is the working file -> https://www.dropbox.com/s/ktkb76xjgnvs3m4/gmaps.html?dl=0 just replace YOUR_API_KEY
    – codtex Mar 22 '17 at 09:34
  • ok so now I see that you haven't added the code that was showing driving distance. I appreciate your effort but I already had a code which was drawing a polyline, I wanted the code to draw a polyline as well as do the calculation of driving distance. If you can see above, I have given two JS codes – Falak Mar 22 '17 at 09:56
  • @Falak use this answer to calculate the distance -> http://stackoverflow.com/a/1502821/5452965. From the above code you have both locations – codtex Mar 22 '17 at 10:01
  • @Falak I made an edit how you can calculate the distance. I hope you will be able to edit your code according the changes. Cheers! – codtex Mar 22 '17 at 10:20