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

时间:2017-03-22 07:22:03

标签: javascript html google-maps google-maps-api-3

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

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

  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用于在地图上显示导航线:

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>

1 个答案:

答案 0 :(得分:3)

好,

首先,您要尝试混合使用不同版本的API。我建议您将所有代码迁移到版本3.然后,您不需要引用两次API,因为这会导致错误,您的<head>应该类似于:

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

注意:API的第3版不需要sensor参数

现在关于你的代码 - 很糟糕!我可以开始解释原因,但这将是一个很长的帖子:)

正如我所说,您的部分代码适用于API版本2,其他版本适用于版本3.当您迁移到单个版本时,它将立即开始工作。请继续阅读官方Google文档 - directionsgeocoding

地图和表单的HTML应如下所示:

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

我不会发表任何评论或向您解释代码,因此您至少可以强迫自己去阅读文档,并尝试自己了解文档的工作原理。

祝你好运!

E D I T

好的,如果你想要这个功能所需的距离:

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

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