虽然制作路线谷歌地图通过JavaScript它不工作在铬但其工作在firefox

时间:2017-03-10 07:09:13

标签: javascript google-maps bootstrap-modal

代码在这里。在localhost它工作正常。我所做的就是在Bootstrap Modal中获取用户位置,然后为用户创建路线图。

< 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>

和html是

   <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>

点击获取地图路线按钮(启动Bootstrap Modal)后,在Firefox中它没有显示地图,直到我点击它,但在Chrome中它甚至不工作无论我是否点击地图都无关紧要。< / p>

1 个答案:

答案 0 :(得分:0)

通常你的代码不起作用,它缺乏逻辑,但我只会引导你。首先,你没有提供正确的HTML,我似乎无法找到地图div,所以如果你还没有写过,那么就把它写在你的HTML中

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

这样你的地图就会显示在chrome&amp; firefox也是,我已经测试过了。 也不要在分隔符或属性之后放置空格,例如

//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 >

应该是

<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>

现在,点击共享位置并在之后提交按钮,您将看到控制台错误。实际上会有2个错误。错误主要在这两行中

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

如果你仔细观察,那么你会发现你正在使用从Vanilla JS到jQuery的这两个变量。如果你真的想以这种方式使用它们,那么脏修复就是从它们中删除var关键字,例如

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

通过这种方式,您当前的脚本将根据您在问题中提出的问题进行操作。在chrome和firefox中显示地图,但在提交时不会分配您当前或指定的地理位置。要实现该特定搜索功能,请参阅此链接https://developers.google.com/maps/documentation/javascript/examples/geocoding-simple

EDIT1:工作小提琴https://jsfiddle.net/yeoman/070chy95/3/

EDIT2:OP有问题,在打开bootstrap模态时,他的地图没有显示。作为使用地理定位API的OP,他应该在模态打开后准确地询问地理坐标。这将通过bootstrap构建回调事件来实现,例如

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

在Firefox 51.0a2和chrome版本56.0.2924.87上进行了测试