Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/html/71.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何使两个谷歌地图脚本在一个页面上独立工作?_Javascript_Html_Google Maps_Google Maps Api 3 - Fatal编程技术网

Javascript 如何使两个谷歌地图脚本在一个页面上独立工作?

Javascript 如何使两个谷歌地图脚本在一个页面上独立工作?,javascript,html,google-maps,google-maps-api-3,Javascript,Html,Google Maps,Google Maps Api 3,我有两个谷歌地图代码。两者都有两个文本框,其中包含地址和一个按钮。第一个计算并显示行驶距离,但不显示地图,第二个显示在谷歌地图上这两个地址之间绘制的导航线。现在,当我将这两种代码组合在一起时,它们都不起作用。我想我正在初始化地图两次,或者这两次之间产生了一些冲突,但我现在不知道在哪里。所以我想知道是否有任何方法可以使这两个独立工作或者同时工作。 我正在使用的脚本标记: <script src="https://maps.googleapis.com/maps/api/js?v=3&

我有两个谷歌地图代码。两者都有两个文本框,其中包含地址和一个按钮。第一个计算并显示行驶距离,但不显示地图,第二个显示在谷歌地图上这两个地址之间绘制的导航线。现在,当我将这两种代码组合在一起时,它们都不起作用。我想我正在初始化地图两次,或者这两次之间产生了一些冲突,但我现在不知道在哪里。所以我想知道是否有任何方法可以使这两个独立工作或者同时工作。 我正在使用的脚本标记:

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

好,

因此,首先您要尝试混合使用不同版本的API。我建议您将所有代码迁移到版本3。那么您不需要引用两次API,因为这会导致错误,您的API应该如下所示:

   <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>
然后您的脚本将如下所示:

<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>
<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>
我不会发表任何评论,也不会向您解释代码,因此您至少可以强迫自己去阅读文档,并尝试自己理解它是如何工作的

祝你好运

爱迪特

好的,如果你想要这个距离,你需要这个函数:

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';
};

请参阅顶部的代码示例,了解如何调用此函数。

您是否可以通过在浏览器的开发人员工具中发布控制台的输出来共享确切的错误。.您已多次在此页面上包含Google Maps API。这可能会导致意外错误。映射:101:295未声明HTML文档的字符编码。如果文档包含US-ASCII范围之外的字符,则在某些浏览器配置中,文档将呈现乱码文本。页面的字符编码必须在文档或传输协议中声明。新的%201.htmljQuery.Deferred异常:a为null wg@Ag@Sb@initGMap@file:///C:/Users/HP/Documents/new%201.html?address1=地址+1&address2=地址+2:142:11@file:///C:/Users/HP/Documents/new%201.html?address1=Address+1&address2=Address+2:147:5 g/TypeError:b未定义[Learn More]映射:30:33 TypeError:uSA未定义[Learn More]common.js:4:85 Google Maps API警告:Noapikes util.js:211:33 TypeError:551;.ej未定义[Learn More]common.js:33:342此解决方案的存储空间,但它仅显示地图,而不是我添加的计算值

nothing@Falak只需按照发布顺序将此代码复制粘贴到空白HTML文件中。代码工作得很好。请阅读并试着理解它实际上是什么。这是工作文件->只需替换你的API键OK,现在我看到你没有添加显示行驶距离的代码。我很感激你的努力,但我已经有了一个代码,它正在绘制一条多段线,我想要这个代码来绘制一条多段线以及计算行驶距离。如果你能看到上面,我已经给出了两个JScodes@Falak使用此答案计算距离->。从上面的代码中,您有两个位置
<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>
<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>
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';
};