Google地图库场所和几何图形在一个HTML页面中协同工作

时间:2014-09-18 06:56:15

标签: javascript google-maps-api-3

我尝试制作一个计算两个位置之间的距离和路线的页面。这些位置由用户通过其文本框中的谷歌地图自动完成功能输入。根据我的知识,它需要2个图书馆工作,地理位置和地方。但是,当导入两个库时,我的程序无法按预期工作。 它只在禁用场所或几何体时工作。

我导入的javascript库如下:

<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&libraries=places,geometry"></script>

JS:

var map;
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();

function initialize() {
    // Buat untuk draggable
    var rendererOptions = {
        draggable: true
    }
    directionsDisplay = new google.maps.DirectionsRenderer(rendererOptions);
    var jakarta = new google.maps.LatLng(-6.195456, 106.822229);
    var mapOptions = {
        zoom: 17,
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        center: jakarta
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
    directionsDisplay.setMap(map);
    directionsDisplay.setPanel(document.getElementById("directionsPanel"));

    start = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('start')), {
        types: ['geocode']
    });
    end = new google.maps.places.Autocomplete(
    /** @type {HTMLInputElement} */
    (document.getElementById('end')), {
        types: ['geocode']
    });

}

// [START region_geolocation]
// Bias the autocomplete object to the user's geographical location,
// as supplied by the browser's 'navigator.geolocation' object.
function geolocate() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(function (position) {
            var geolocation = new google.maps.LatLng(
            position.coords.latitude, position.coords.longitude);
            start.setBounds(new google.maps.LatLngBounds(geolocation,
            geolocation));
            end.setBounds(new google.maps.LatLngBounds(geolocation,
            geolocation));
        });
    }
}

function calcRoute(start, end) {

    var request = {
        origin: start,
        destination: end,
        provideRouteAlternatives: true,
        avoidHighways: true,
        avoidTolls: true,
        travelMode: google.maps.TravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {

            // Resize the map canvas to accomodate
            // the textual directions panel
            map_canvas.style.width = '70%';
            directionsPanel.style.display = 'inline';
            // Request map resize.
            google.maps.event.trigger(map, "resize");

            // display the directions
            directionsDisplay.setDirections(response);

            // Display the distance:
            document.getElementById('distance').innerHTML += response.routes[0].legs[0].distance.value + " Meter";

            // Display the duration:
            document.getElementById('duration').innerHTML += response.routes[0].legs[0].duration.value + " Detik";

            //  Define perhitungan ongkos
            var subTotal = 0.0;
            var hargaPerMeter = 3;
            var argoMinimum = 15000;
            var jarakMinimum = 5000;
            var jarakAntar = parseInt(response.routes[0].legs[0].distance.value);

            if (jarakAntar < jarakMinimum) {
                subTotal = argoMinimum;
                document.getElementById('ongkos').innerHTML = " Rp. " + subTotal.toFixed(2);
            } else {
                // Hitung ongkos berdasarkan jarak
                subTotal += (jarakAntar * hargaPerMeter);
                document.getElementById('ongkos').innerHTML = " Rp. " + subTotal.toFixed(2);
            }
        } else {
            alert('Kesalahan pada alamat !');
        }

    });

    function hitungOngkos() {
        var subTotal = 0.0;
        var hargaPerMeter = 3000;
        var dropOffCharge = 2.50;
        var overTwoPassengerCharge = 2.00;
        var jarakAntar = (document.getElementById('distance').innerHTML += response.routes[0].legs[0].distance.value) / 1000;
        var passengers = Number(document.getElementById("passengers").value);

        // kalo goncengan, tambahan orang kena Rp. 20.000
        if (passengers > 2) {
            subTotal = overTwoPassengerCharge * (passengers - 2);
        }

        // Hitung ongkos berdasarkan jarak
        subTotal += parseInt(jarakAntar * 5) * hargaPerMeter;
        subTotal += dropOffCharge;
        // cetak ongkos pada element div. toFixed masukan receh pada perhitungan
        document.getElementById('ongkos').innerHTML = " $" + subTotal.toFixed(0);
    }
}

/*
 * Show the textual directions panel, resize the map canvas
 * trigger resize event on map, and compute the directions             
 * Note that start and end corresponds to the input id of
 * the controls
 */
function showDirectionsPanelandCalculate() {
    if (start.value.length == 0 || end.value.length == 0) {
        return;
    }
    calcRoute(start.value, end.value);

}

/*
 * Hide the textual directions panel resize map
 * canvas to original size, trigger resize on
 * map.  You can also recalculate directions if
 * desired.
 */
function hideDirectionsPanel() {

    map_canvas.style.width = '100%';
    directionsPanel.style.display = 'none';
    google.maps.event.trigger(map, "resize");

}

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

CSS:

body {
    width:950px;
}
/* Controls that takes the start/end address.
        */
 #controls {
    background-color: lightgray;
    font-size: 11px;
    position:fixed;
    /*  bottom:-0px; */
    margin-bottom: 20px;
    left:5px;
    border:1px solid darkgray;
    padding:5px;
    z-index:10000;
}
/*  Map canvas */
 #map_canvas {
    float:left;
    width:100%;
    height:700px;
}
/*  Textual directions frame */
 #directionsPanel {
    float:right;
    display: none;
    width:29%;
    height: 700px;
    font-size: 12px;
    margin-left: 2px;
    overflow: scroll;
}

HTML:

<head>
    <title>Google Directions</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <!-- Libaray untuk auto alamat -->
    <script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=geometry,places"></script>
    <!-- Libaray untuk hitung jarak -->
    <!-- <script src="https://maps.googleapis.com/maps/api/js?v=3&sensor=false"></script> -->
</head>
<body onload="initialize()">
    <!-- The controls are in a floating frame near the bottom of map --> <span id="controls">
            <input id="start" placeholder="Alamat Pengirim" onFocus="geolocate()" type="text" />
            <input id="end" placeholder="Alamat Tujuan" onFocus="geolocate()" type="text" />            
            <button onclick="showDirectionsPanelandCalculate();return false">
                Hitung Jarak
            </button>            
        </span>

    <!-- Map canvas -->
    <div id="map_canvas"></div>
    <!-- Directions in text -->
    <div id="directionsPanel">
        <button onclick="hideDirectionsPanel();return false;">Hide</button>
    </div>
    <div id="duration">Perkiraan Waktu:</div>
    <div id="distance">Jarak:</div>
    <div id="ongkos">Ongkos Antar:</div>
</body>

1 个答案:

答案 0 :(得分:0)

我尝试使用javascript日志调试您的代码。 我认为您的问题出在您的自定义函数calcRoute(start,end)

我尝试直接传递变量而不使用函数参数,如下所示

function calcRoute() 
{
    var doStart = document.getElementById('start').value;
    var doFinish = document.getElementById('end').value;

    var request = {
        origin: doStart,
        destination: doFinish,
        provideRouteAlternatives: true,
        avoidHighways: true,
        avoidTolls: true,
        travelMode: google.maps.TravelMode.DRIVING
    };

    directionsService.route(request, function (response, status) {
        if (status == google.maps.DirectionsStatus.OK) {

            // Resize the map canvas to accomodate
            // the textual directions panel
            map_canvas.style.width = '70%';
            directionsPanel.style.display = 'inline';
            // Request map resize.
            google.maps.event.trigger(map, "resize");

            // display the directions
            directionsDisplay.setDirections(response);

            // Display the distance:
            document.getElementById('distance').innerHTML += response.routes[0].legs[0].distance.value + " Meter";

            // Display the duration:
            document.getElementById('duration').innerHTML += response.routes[0].legs[0].duration.value + " Detik";

我还对此功能进行了一些修改

function showDirectionsPanelandCalculate() 
{
    if (start.value == 0 || end.value == 0) {
        return;
    }
    calcRoute(start.value, end.value);

}

附上jsfiddle链接here