简体   繁体   中英

Javascript: get driving distance and time and show current location in google map?

I'm using the following codes to get driving distance and time and display the current location in Google map using javascript.

The values of longitude and latitude and post codes etc comes from php/mysql.

Everything works fine.

However, the issue that I have is that something stops the javascript codes to work together on the same page and they only work if they are in separate pages!

So basically I can only use one of the Javascript codes in a page and if I use both codes in the same page, the only code that works would be the driving distance and time code which I have no idea why.

here is my driving distance and time calculation code:

<script>
    (function () {


        var directionsService = new google.maps.DirectionsService(),
            directionsDisplay = new google.maps.DirectionsRenderer(),
            createMap = function (start) {
                var travel = {
                        origin : (start.coords)? new google.maps.LatLng(start.lat, start.lng) : start.address,
                        destination : "<?php echo $CUpostCode; ?>",
                        travelMode : google.maps.DirectionsTravelMode.DRIVING
                        // Exchanging DRIVING to WALKING above can prove quite amusing :-)
                    },
                    mapOptions = {
                        zoom: 10,
                        // Default view: downtown Stockholm
                        center : new google.maps.LatLng(59.3325215, 18.0643818),
                        mapTypeId: google.maps.MapTypeId.ROADMAP
                    };

                map = new google.maps.Map(document.getElementById("map"), mapOptions);
                directionsDisplay.setMap(map);
                directionsDisplay.setPanel(document.getElementById("map-directions"));
                directionsService.route(travel, function(result, status) {
                    if (status === google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(result);
                    }
                });
            };

            // Check for geolocation support    
            if (navigator.geolocation) {



                window.onload = (function (position) {
                        // Success!
                        createMap({
                            coords : true,
                            //lat : position.coords.latitude,
                            //lng : position.coords.longitude


                            lat : <?php echo $curLat; ?>,
                            lng : <?php echo $curLon; ?>
                        });
                    }, 
                    function () {
                        // Gelocation fallback: Defaults to Stockholm, Sweden
                        createMap({
                            coords : true,
                            //lat : position.coords.latitude,
                            //lng : position.coords.longitude


                            lat : <?php echo $curLat; ?>,
                            lng : <?php echo $curLon; ?>
                        });
                    }
                );
            }
            else {
                // No geolocation fallback: Defaults to Lisbon, Portugal
                createMap({
                            coords : true,
                            //lat : position.coords.latitude,
                            //lng : position.coords.longitude


                            lat : <?php echo $curLat; ?>,
                            lng : <?php echo $curLon; ?>
                });


            }
    })();
</script>

and this is the code for showing the Location in the google map:

<script>
    function showCurrentLocation(position)
    {
        var latitude = <?php echo $curLat; ?>;
        var longitude = <?php echo $curLon; ?>;
        var coords2 = new google.maps.LatLng(latitude, longitude);

        var mapOptions2 = {
        zoom: 15,
        center: coords2,
        mapTypeControl: true,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    //create the map, and place it in the HTML map div
    map2 = new google.maps.Map(
    document.getElementById("mapPlaceholder"), mapOptions2
    );

    //place the initial marker
    var marker2 = new google.maps.Marker({
    position: coords2,
    map: map2,
    title2: "Current location!"
    });
    }
</script>

and I have these two lines in my page's header:

<script src="http://maps.google.se/maps/api/js?sensor=false"></script>
 <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

Could someone please let me know whats the conflict between these two codes that stops them working in the same page?

You added: I was calling it like so: onload="showCurrentLocation()"

you are overwriting the onload event. Using google.maps.addDomListener instead will solve that issue.

google.maps.event.addDomListener(window,'load',showCurrentLocation);

working fiddle

working code snippet:

 var curLat = 45; var curLon = -117; (function () { var directionsService = new google.maps.DirectionsService(), directionsDisplay = new google.maps.DirectionsRenderer(), createMap = function (start) { var travel = { origin: (start.coords) ? new google.maps.LatLng(start.lat, start.lng) : start.address, destination: "07646", travelMode: google.maps.DirectionsTravelMode.DRIVING // Exchanging DRIVING to WALKING above can prove quite amusing :-) }, mapOptions = { zoom: 10, // Default view: downtown Stockholm center: new google.maps.LatLng(59.3325215, 18.0643818), mapTypeId: google.maps.MapTypeId.ROADMAP }; map = new google.maps.Map(document.getElementById("map"), mapOptions); directionsDisplay.setMap(map); directionsDisplay.setPanel(document.getElementById("map-directions")); directionsService.route(travel, function (result, status) { if (status === google.maps.DirectionsStatus.OK) { directionsDisplay.setDirections(result); } }); }; // Check for geolocation support if (navigator.geolocation) { window.onload = (function (position) { // Success! createMap({ coords: true, //lat : position.coords.latitude, //lng : position.coords.longitude lat: curLat, lng: curLon }); }, function () { // Gelocation fallback: Defaults to Stockholm, Sweden createMap({ coords: true, //lat : position.coords.latitude, //lng : position.coords.longitude lat: curLat, lng: curLon }); }); } else { // No geolocation fallback: Defaults to Lisbon, Portugal createMap({ coords: true, //lat : position.coords.latitude, //lng : position.coords.longitude lat: curLat, lng: curLon }); } })(); function showCurrentLocation(position) { var latitude = curLat; var longitude = curLon; var coords2 = new google.maps.LatLng(latitude, longitude); var mapOptions2 = { zoom: 15, center: coords2, mapTypeControl: true, mapTypeId: google.maps.MapTypeId.ROADMAP }; //create the map, and place it in the HTML map div map2 = new google.maps.Map( document.getElementById("mapPlaceholder"), mapOptions2); //place the initial marker var marker2 = new google.maps.Marker({ position: coords2, map: map2, title2: "Current location!" }); } google.maps.event.addDomListener(window,'load',showCurrentLocation); 
 html, body, #map, #map-directions, #mapPlaceholder { height:100%; width:100%; } 
 <script src="http://maps.google.com/maps/api/js"></script> <table> <tr> <td> <div id="mapPlaceholder" style="height:500px; width:500px;"></div> </td> </tr> <tr> <td> <div id="map" style="height:500px; width:500px;"></div> </td> </tr> <tr> <td> <div id="map-directions"></div> </td> </tr> </table> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM