简体   繁体   中英

while making a route google map through javascript its not working in chrome but its working in firefox

code is here. In localhost it is working fine. All i do is getting user location in the Bootstrap Modal and then creating a route map for a user.

< script src = "https://maps.google.com/maps/api/js?key=***************************&sensor=true" > < /script> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" > < /script> < script >

function calculateRoute(from, to) {
    var myLatLng = {
        lat: 26.929307,
        lng: 75.884867
    };

    // Center initialized to HeiwaHeaven
    var myOptions = {
        zoom: 15,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };

    // Draw the map
    var mapObject = new google.maps.Map(document.getElementById("map"), myOptions);

    var directionsService = new google.maps.DirectionsService();
    var directionsRequest = {
        origin: from,
        destination: to,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.METRIC
    };
    directionsService.route(
        directionsRequest,
        function(response, status) {
            if (status == google.maps.DirectionsStatus.OK) {
                new google.maps.DirectionsRenderer({
                    map: mapObject,
                    directions: response
                });

                $('.distance-in-km').text(response.routes[0].legs[0].distance.value / 1000 + "km");

                alert(response.routes[0].legs[0].distance.value / 1000 + "km"); // the distance in metres
            } else
                $("#error").append("Unable to retrieve your route<br />");
        }
    );
}

$(document).ready(function() {
// If the browser supports the Geolocation API
if (typeof navigator.geolocation == "undefined") {
    $("#error").text("Your browser doesn't support the Geolocation API");
    return;
}

navigator.geolocation.getCurrentPosition(function(position) {
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
            "location": new google.maps.LatLng(position.coords.latitude, position.coords.longitude)
        },
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                calculateRoute(results[0].formatted_address, "Jamdoli Chauraha To Jaisinghpura Khor Road, Near Keshav Vidyapeeth, Jaipur, Agra Rd, Jaipur");
            } else {
                var marker = new google.maps.Marker({
                    position: myLatLng,
                    title: 'Hello World!'
                });

                marker.setMap(mapObject);

                $("#error").append("Unable to retrieve your address<br />");
            }
        });
});

calculateRoute($("#from").val(), "Jamdoli Chauraha To Jaisinghpura Khor Road, Near Keshav Vidyapeeth, Jaipur, Agra Rd, Jaipur");

$("#calculate-route").submit(function(event) {
    event.preventDefault();

    calculateRoute($("#from").val(), "Jamdoli Chauraha To Jaisinghpura Khor Road, Near Keshav Vidyapeeth, Jaipur, Agra Rd, Jaipur");
});

$('.verify-location > a').click(function() {
    $('.verify-location').hide();
    $('#calculate-route').show();
});
}); < /script>

and the html is

   <button type="button" class="close" data-dismiss="modal">&times;</button>
 <div class="verify-location">Is the your location incorrect? <a>Click here to enter your location manually</a></div>
   <form id="calculate-route" name="calculate-route" action="#" method="get">
    <label for="from">From:</label>
      <input type="text" id="from" name="from" placeholder="An address" size="30" />
     <button type="submit">Submit</button>

Upon clicking Get Map route button(which launch Bootstrap Modal), In Firefox it did not show the map until i click on it but in chrome its not even working Doesn't matter if i click on the map or not.

Generally your code is not working, It lacks logic but i'll guide you only. First you didn't provide correct HTML, i can't seems to find map div so if you haven't wrote that already then write this in your HTML

    <div id="map" style="height: 400px; width: 500px;"></div>

This way your map will show on chrome & firefox as well, I tested already. Also don't put space after delimiters or attributes for example

//This is wrong spacing after "<" or ">"    
< script src = "https://maps.google.com/maps/api/js?key=***************************&sensor=true" > < /script> < script src = "https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" > < /script> < script >

it should be

<script src="https://maps.google.com/maps/api/js?key=***************************&sensor=true"></script> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>

Now, Upon clicking share location and submit button afterwards, You will be presented with console errors. There will be 2 errors actually. Errors are mainly in these two lines

1 - ReferenceError: myLatLng is not defined 
2 - ReferenceError: mapObject is not defined

If you see closely, Then you will see you are using these 2 variables from Vanilla JS to jQuery. If you really want to use them this way then dirty fix would be to remove var keyword from them, such as

myLatLng = {
    lat: 26.929307,
    lng: 75.884867
} // NOTE: no VAR in start
 mapObject = new google.maps.Map(document.getElementById("map"), myOptions);  // NOTE: no VAR in start

This way your current script will work according to what you asked in the question & show map in chrome and firefox but it will not assign your current or specified Geo Location upon submitting. To implement that particular search functionality, see this Link https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

EDIT1: working fiddle https://jsfiddle.net/yeoman/070chy95/3/

EDIT2: OP has problem that upon opening bootstrap modal his map was not being shown. As OP using geolocation API, he should ask for geo co-ordinates exactly after modal is opened. This will be achieved with bootstrap build callback events eg.

 $('#myModal').on('shown.bs.modal', function (e) {
    // code to execute
    // this is the place where map should ask for geolocation
 }); 

Tested both on Firefox 51.0a2 and chrome Version 56.0.2924.87

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