我希望从google maps api获取的数据被插入到我的(mysql)数据库中。我希望只需单击一下,就可以将所有备用路由的source_address,destination_address,distance,duration的持续时间插入到我的mysql数据库中我写的get_route函数。
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay; // The whole map rendering or displaying.
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = response.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
答案 0 :(得分:0)
你必须使用AJAX。获取source
,destination
,distance
和duration
等所有详细信息后,使用AJAX收集并打包所有数据,并将它们异步发送到其他页面,例如< strong> saveDetails.php 将所有数据保存到数据库表中。
这是AJAX参考:
所以你的JavaScript应该是这样的:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var directionsDisplay; // The whole map rendering or displaying.
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute() {
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function (response, status) { // RouteService
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
}
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.DRIVING,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status) {
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
var distance = response.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = response.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;
// Here's your AJAX request
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState == 4 && httpRequest.status == 200) {
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "saveDetails.php", true);
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("source=" + source + "&destination=" + destination + "&distance=" + distance + "&duration=" + duration);
} else {
alert("Unable to find the distance via road.");
}
});
}
</script>
在 saveDetails.php 页面上,处理您的数据,如下所示:
<?php
if(isset($_POST['source']) && isset($_POST['destination']) && isset($_POST['distance']) && isset($_POST['duration'])){
// do your database operations
}
?>
根据您的要求,
我想在表格中存储多个替代路线的距离和持续时间...我想让我的数据库成为旅行(trip_id,源,目的地)路线(route_id.trip_id,距离,持续时间)一对多的关系旅行和路线之间。 trip_id是外键
这是完整的解决方案:
首先,创建两个名为trip
和route
的表。他们的结构将是这样的:
CREATE TABLE trip(
trip_id INT(11) NOT NULL AUTO_INCREMENT,
source VARCHAR(255) NOT NULL,
destination VARCHAR(255) NOT NULL,
PRIMARY KEY(trip_id)
);
CREATE TABLE route(
route_id INT(11) NOT NULL AUTO_INCREMENT,
trip_id INT(11) NOT NULL,
distance VARCHAR(50) NOT NULL,
duration VARCHAR(50) NOT NULL,
PRIMARY KEY(route_id),
FOREIGN KEY(trip_id) REFERENCES trip(trip_id)
);
现在提供您的HTML和JavaScript代码,
<html>
<head>
<title></title>
<style type="text/css">
body
{
font-family: Arial;
font-size: 10pt;
}
</style>
</head>
<body>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
<script type="text/javascript">
var source, destination;
var routeArr = [];
var directionsDisplay; // The whole map rendering or displaying.
var globalResponse;
var directionsService = new google.maps.DirectionsService(); // For Availing the Direction Services provided by APIs
google.maps.event.addDomListener(window, 'load', function () { // This acts as a pageload Function
new google.maps.places.SearchBox(document.getElementById('txtSource'));
new google.maps.places.SearchBox(document.getElementById('txtDestination'));
directionsDisplay = new google.maps.DirectionsRenderer({ 'draggable': true });
});
function GetRoute()
{
var kolkata = new google.maps.LatLng(22.7383075, 88.454424); // Center of the Map
var mapOptions = { // Setting the View of the Map
zoom: 7,
center: kolkata
};
map = new google.maps.Map(document.getElementById('dvMap'), mapOptions); // Variable for map view
directionsDisplay.setMap(map); // Map view
directionsDisplay.setPanel(document.getElementById('dvPanel')); //Panel View
//------------------------------DIRECTIONS AND ROUTE------------------------------------------------------
source = document.getElementById("txtSource").value;
destination = document.getElementById("txtDestination").value;
var request = // variable request
{ // DirectionsService
origin: source,
destination: destination,
provideRouteAlternatives: true,
travelMode: google.maps.TravelMode.TRANSIT
};
directionsService.route(request, function (response, status){ // RouteService
if (status == google.maps.DirectionsStatus.OK){
/*for (var i = 0; i < response.routes.length; i++) {
var dr = new google.maps.DirectionsRenderer();
dr.setDirections(response);
// Tell the DirectionsRenderer which route to display
dr.setRouteIndex(i);
dr.setMap(map);
// Code ommited to display distance and duration
}*/
globalResponse = response;
routeArr = [];
for(i=0;i<globalResponse.routes.length;i++){
routeArr.push([globalResponse.routes[i].legs[0].distance.text, globalResponse.routes[i].legs[0].duration.text]);
}
var s = 'Possible routes are: <br />';
for(i = 0; i < routeArr.length; ++i){
s += "Distance: " + routeArr[i][0] + ", " + "Duration: " + routeArr[i][1] + "<br />";
}
document.getElementById("dvDistance").innerHTML = s;
directionsDisplay.setDirections(response);
}
// Here's the AJAX request
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, IE7+ ...
httpRequest = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 6 and older
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
httpRequest.onreadystatechange = function() { // here the function name that is designed to handle the response
if (httpRequest.readyState == 4 && httpRequest.status == 200) { //200 OK response code. // 4 is complete response received
alert(httpRequest.responseText);
}
};
httpRequest.open("POST", "mapdb.php", true); // here true means asynchronously server is called,i.e,without page reloading
httpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
httpRequest.send("source=" + source + "&destination=" + destination + "&routes=" + JSON.stringify(routeArr));
});
//-----------------------------DISTANCE AND DURATION----------------------------------------------------
var service = new google.maps.DistanceMatrixService(); // Different Services Provided by APIs
service.getDistanceMatrix({
origins: [source],
destinations: [destination],
travelMode: google.maps.TravelMode.TRANSIT,
unitSystem: google.maps.UnitSystem.METRIC,
avoidHighways: false,
avoidTolls: false
}, function (response, status){
if (status == google.maps.DistanceMatrixStatus.OK && response.rows[0].elements[0].status != "ZERO_RESULTS") {
/*var distance = globalResponse.rows[0].elements[0].distance.text; // Distance Calculation From data provide by APIs
var duration = globalResponse.rows[0].elements[0].duration.text; // Duration Calculation From data provide by APIs
var distance = globalResponse.routes[0].legs[0].distance.text;
var duration = globalResponse.routes[0].legs[0].duration.text;
var dvDistance = document.getElementById("dvDistance"); // This Variable is for Fetching the Routes distance and displaying it on web page.
dvDistance.innerHTML = "";
dvDistance.innerHTML += "Distance: " + distance + "<br />";
dvDistance.innerHTML += "Duration:" + duration;//+ " "+typeof response.routes.length;*/
}else {
alert("Unable to find the distance via road.");
}
});
}
</script>
<table border="0" cellpadding="0" cellspacing="3">
<tr>
<td colspan="2">
Source:
<input type="text" id="txtSource" style="width: 200px" />
Destination:
<input type="text" id="txtDestination" style="width: 200px" />
Travel Mode:
<select>
<option value="1" >Driving</option>
<option value="2">Cycling</option>
<option value="3">Transit</option>
<option value="4"selected>Walking</option>
</select>
<br />
<input type="button" value="Get Route" onclick="GetRoute()" />
<hr />
</td>
</tr>
<tr>
<td colspan="2">
<div id="dvDistance">
</div>
</td>
</tr>
<tr>
<td>
<div id="dvMap" style="width: 800px; height: 500px">
</div>
</td>
<td>
<div id="dvPanel" style="width: 500px; height: 500px">
</div>
</td>
</tr>
</table>
<br>
</body>
</html>
最后,您的 mapdb.php 页面将如下所示:
<?php
if(isset($_POST['source'], $_POST['destination']) && count($_POST['routes'])){
$routes_array = json_decode($_POST['routes'], true);
// Create connection
$conn = new mysqli("localhost", "root", "", "testdb");
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$source = $_POST['source'];
$destination = $_POST['destination'];
$query = "INSERT INTO trip(source, destination) VALUES('{$source}', '{$destination}')";
if($conn->query($query)){
$trip_id = $conn->insert_id;
foreach($routes_array as $route){
$distance = $route[0];
$duration = $route[1];
$query = "INSERT INTO route(trip_id, distance, duration) VALUES({$trip_id}, '{$distance}', '{$duration}')";
$conn->query($query);
}
echo "success";
}else{
echo "Record couldn't be inserted";
}
// Close connection
$conn->close();
}
?>