如何解决Google Maps onChangeHandler函数
请帮助我!以下是我的Google Maps Code。如何实现onChangeHandler
函数?
我希望Google地图在两个地址均可用时显示行驶方向,而在单击“提交”按钮时显示不。
该代码运行良好,但只有在用户单击“提交”后,Google Maps的行车路线才会显示,在大多数情况下,甚至不会向用户显示,除非该用户的网络速度较慢。
var onChangeHandler = function() {
calculateAnddisplayRoute(directionsService,directionsdisplay);
};
document.getElementById('origin').addEventListener('change',onChangeHandler);
document.getElementById('destination').addEventListener('change',onChangeHandler);
<!DOCTYPE html>
<html>
<head>
<Meta charset="UTF-8">
<Meta content="width=device-width,initial-scale=1,maximum-scale=1,shrink-to-fit=no" name="viewport">
<title><?PHP echo $title ; ?></title>
<link rel="shortcut icon" type="image/x-icon" href="<?PHP echo base_url(); ?>assets/home/img/favicon.ico">
<!-- General CSS Files -->
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/modules/bootstrap/css/bootstrap.min.css">
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/modules/fontawesome/css/all.min.css">
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/modules/ionicons/css/ionicons.min.css">
<!-- Template CSS -->
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/css/style.css">
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/css/components.css">
<!-- Toast/ Flash Message CSS file -->
<link href="<?PHP echo base_url(); ?>assets/css/toast.css" rel="stylesheet">
<!-- Start GA -->
<?PHP if ($this->uri->segment(1) == "settings"): ?>
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/modules/codemirror/lib/codemirror.css">
<link rel="stylesheet" href="<?PHP echo base_url(); ?>assets/modules/codemirror/theme/duotone-dark.css">
<?PHP endif; ?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script defer
src="https://maps.googleapis.com/maps/api/js?libraries=places&language=en&key=AIzaSyCIXcLoqDzQvp39vsyI6J_6X_33CkIUlN0"
type="text/javascript"></script>
<style>
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Modifying the input Box */
input[type="text"],input[type="email"],input[id="from_places"],input[id="to_places"],input[type="tel"],select.form-control {
background: transparent;
border-top: none;
border-left: none;
border-right: none;
border-buttom: 1px solid #999;
-webkit-Box-shadow: none;
Box-shadow: none;
border-radius: 10;
}
/* Optional: Makes the sample page fill the window. */
html,body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
bottom: 1px;
top: 15px;
left: 0;
height: 100%;
z-index: 5;
padding: 5px;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 1px;
}
</style>
</head>
<body>
<!-- website NavBar -->
<!-- Main Content -->
<div id="floating-panel">
<form id="distance_form" action="<?PHP echo base_url('deliver/getdistance') ?>" method="post">
<div class="card">
<div class="card-header">
<a href="#" onclick="window.goBack()"><i class="fas fa-arrow-left btn btn-xl"></i> </a><h4> DeiverASAP,Quicker and Better</h4>
<div class="card-header-action">
<a data-collapse="#mycard-collapse" class="btn btn-icon btn-primary" href="#"><i class="fas fa-minus"></i></a>
</div>
</div>
<div class="collapse show" id="mycard-collapse">
<div class="card-body">
<div class="form-group">
<div class="input-group mb-3">
<input class="form-control" id="from_places" placeholder="From Where ?"/>
<input id="origin" name="from" required="" type="hidden"/>
<div class="input-group-append">
<a class="btn btn-primary" onclick="getCurrentPosition()"><i class="ion-android-pin"></i></a>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<input type="text" name="firstname" placeholder="First Name" class="form-control" required>
</div>
<div class="form-group col-md-6">
<input type="text" name="lastname" placeholder="Last Name" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<input type="tel" name="phone" placeholder="Phone Number" class="form-control" required>
</div>
<div class="form-group col-md-6">
<input type="email" name="email" placeholder="Email" class="form-control" required>
</div>
</div>
<div class="form-group">
<div class="input-group mb-3">
<input class="form-control" id="to_places" placeholder="To Where ?"/>
<input id="destination" name="to" required="" type="hidden"/>
<div class="input-group-append">
<a class="btn btn-primary" onclick="getCurrentPosition()"><i class="ion-android-pin"></i></a>
</div>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<input type="text" name="destfirst" placeholder="First Name" class="form-control" required>
</div>
<div class="form-group col-md-6">
<input type="text" name="destlast" placeholder="Last Name" class="form-control" required>
</div>
</div>
<div class="row">
<div class="form-group col-md-6">
<input type="tel" name="destphone" placeholder="Phone Number" class="form-control" required>
</div>
<div class="form-group col-md-6">
<input type="email" name="destemail" placeholder="Email" class="form-control" required>
</div>
</div>
<input type="text" id="travel_mode" value="DRIVING" name="travel_mode" hidden>
<div class="form-group">
<input class="btn btn-primary" type="submit" value="Submit"/>
</div>
<div id="result" class="hide">
<ul class="list-group">
<li id="in_mile" hidden></li>
<li id="in_kilo" hidden></li>
<li id="duration_text" hidden></li>
<div id="hide"></div>
</ul>
</div>
</form>
</div>
</div>
</div>
</div>
<!-- Website Map and Form starts here -->
<div id="map"></div>
</div>
</section>
</div>
<script>
$(function () {
var origin,destination,map;
// add input listeners
google.maps.event.addDomListener(window,'load',function (listener) {
setDestination();
initMap();
});
// init or load map
function initMap() {
var myLatLng = {
lat: 8.497860,lng: 4.585010
};
map = new google.maps.Map(document.getElementById('map'),{zoom: 10,center: myLatLng,});
}
function setDestination() {
var from_places = new google.maps.places.Autocomplete(document.getElementById('from_places'));
var to_places = new google.maps.places.Autocomplete(document.getElementById('to_places'));
google.maps.event.addListener(from_places,'place_changed',function () {
var from_place = from_places.getPlace();
var from_address = from_place.formatted_address;
$('#origin').val(from_address);
});
google.maps.event.addListener(to_places,function () {
var to_place = to_places.getPlace();
var to_address = to_place.formatted_address;
$('#destination').val(to_address);
});
}
function displayRoute(travel_mode,origin,directionsService,directionsdisplay) {
directionsService.route({
origin: origin,destination: destination,travelMode: travel_mode,avoidTolls: true
},function (response,status) {
if (status === 'OK') {
directionsdisplay.setMap(map);
directionsdisplay.setDirections(response);
} else {
directionsdisplay.setMap(null);
directionsdisplay.setDirections(null);
alert('Could not display directions due to: ' + status);
}
});
}
// calculate distance,after finish send result to callback function
function calculatedistance(travel_mode,destination) {
var distanceMatrixService = new google.maps.distanceMatrixService();
distanceMatrixService.getdistanceMatrix(
{
origins: [origin],destinations: [destination],travelMode: google.maps.TravelMode[travel_mode],unitSystem: google.maps.UnitSystem.IMPERIAL,// miles and feet.
// unitSystem: google.maps.UnitSystem.metric,// kilometers and meters.
avoidHighways: false,avoidTolls: false
},save_results);
}
// save distance results
function save_results(response,status) {
if (status != google.maps.distanceMatrixStatus.OK) {
$('#result').html(err);
} else {
var origin = response.originAddresses[0];
var destination = response.destinationAddresses[0];
if (response.rows[0].elements[0].status === "ZERO_RESULTS") {
$('#result').html("Sorry,Delivery service not available between " + origin + " and " + destination);
} else {
var distance = response.rows[0].elements[0].distance;
var duration = response.rows[0].elements[0].duration;
var distance_in_kilo = distance.value / 1000; // the kilo meter
var distance_in_mile = distance.value / 1609.34; // the mile
var duration_text = duration.text;
appendResults(distance_in_kilo,distance_in_mile,duration_text);
console.log(distance_in_kilo,duration_text);
sendAjaxRequest(origin,distance_in_kilo,duration_text);
}
}
}
// append html results
function appendResults(distance_in_kilo,duration_text) {
$("#result").removeClass("hide");
$('#in_mile').html("distance in Miles : <span class='badge badge-pill badge-secondary'>" + distance_in_mile.toFixed(2) + "</span>");
$('#in_kilo').html("distance in Kilometer: <span class='badge badge-pill badge-secondary'>" + distance_in_kilo.toFixed(2) + "</span>");
$('#duration_text').html("Duration: <span class='badge badge-pill badge-success'>" + duration_text + "</span>");
}
// send ajax request to save results in the database
function sendAjaxRequest(origin,duration_text) {
var username = $('#username').val();
var travel_mode = $('#travel_mode').find(':selected').text();
$.ajax({
url: '<?= base_url('user/common') ?>',type: 'POST',data: {
username,travel_mode,duration_text
},success: function (response) {
console.log(response);
window.location.href='<?= base_url('user/dashboard') ?>';
},error: function (jqXHR,textStatus,errorThrown) {
console.log(textStatus,errorThrown);
}
});
}
// on submit display route,append results and send calculatedistance to ajax request
$('#distance_form').submit(function (e) {
e.preventDefault();
var origin = $('#origin').val();
var destination = $('#destination').val();
var travel_mode = $('#travel_mode').val();
var directionsdisplay = new google.maps.DirectionsRenderer({'draggable': false});
var directionsService = new google.maps.DirectionsService();
displayRoute(travel_mode,directionsdisplay);
calculatedistance(travel_mode,destination);
});
});
// get current Position
function getCurrentPosition() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(setCurrentPosition);
} else {
alert("Geolocation is not supported by this browser.")
}
}
// get formatted address based on current position and set it to input
function setCurrentPosition(pos) {
var geocoder = new google.maps.Geocoder();
var latlng = {lat: parseFloat(pos.coords.latitude),lng: parseFloat(pos.coords.longitude)};
geocoder.geocode({ 'location' :latlng },function (responses) {
console.log(responses);
if (responses && responses.length > 0) {
$("#origin").val(responses[1].formatted_address);
$("#from_places").val(responses[1].formatted_address);
// console.log(responses[1].formatted_address);
} else {
alert("Cannot determine address at this location.")
}
});
}
</script>
<?PHP $this->load->view('dist/_partials/js'); ?>
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。