谷歌地图库位置和几何图形在一个HTML页面中协同工作

Google Map Library Places and Geometry working together in one HTML page

本文关键字:HTML 一个 协同工作 位置 几何图形 谷歌地图      更新时间:2023-09-26

我试图制作一个页面来计算两个位置之间的距离和路线。这些位置是由具有自动完成功能的用户从谷歌地图的文本框中输入的。据我所知,它需要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>

我尝试使用javascript日志调试您的代码。我认为你的问题在于你的自定义函数calcRoute(开始,结束)

我试图在没有函数参数的情况下直接传递变量,使其低于

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