如何在谷歌地图API中给出动态纬度和经度值



我正在使用Google Maps API。在这里,我给出静态纬度和经度意味着它工作正常,但我的要求是在AJAX响应中,我传递latitdute和经度值,而不是静态latitdute和经度值,我想给出我的动态latitdute和经度值(来自我的json响应(。

function initMap(lat,long) {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {
lat: lat,
lng: long
} // Starting Point Marathahalli
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
/* configure waypoints */
var waypts = [];
waypts.push({
location: {
lat: lat,
lng: long
}, // HAL
stopover: true
}, {
location: {
lat:lat,
lng:long
},
stopover: true
});
directionsService.route({
origin: {
lat: lat,
lng: long
}, // Haight.
destination: {
lat:lat,
lng: long
}, // Ending Point Shivaji Nagar.
travelMode: google.maps.TravelMode[selectedMode],
waypoints: waypts
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<form id="testForm">
<select name="tripId">
		<option value="">Select trip</option>
		<option value="1">1</option>
		<option value="2">2</option>
	</select>
<button type="button" id="btn-submit">submit</button>
</form><br></br>
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
</select>
</div>
<div id="map"></div>
</body>
</html>

我尝试使用onclick事件的代码:

$('#btn-submit').click(function(e){
e.preventDefault();
$.ajax({
type:'POST',
url :"getLatLan.php",
data : $('#testForm').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data);
console.log(res);
if(res['status']=='success'){
var position=res.data;
for (var i=0; i<position.length; i++)
{
initMap(position[i].latitude,position[i].longitude);
}

}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
});

我在AJAX 中得到回复 (console.log(res);(:

{
"status": "success",
"count": 2,
"data": [
{
"tripId": "1",
"pickUpLatitidute": "",
"pickUpLongitude": "",
"cabNo": "Ad2K2001",
"driverId": "G2E100",
"routeId": "1",
"tripDate": "2017-08-01 15:45:55",
"startTime": "15:45:55",
"endTime": "14:48:55",
"shiftId": "1",
"tripStatus": "0",
"id": "1",
"empId": "G2E201",
"callStartTime": "",
"callEndTime": "",
"cabReachingTime": "",
"pickupTime": "15:50:02",
"dropTime": "",
"dropStatus": "0",
"otp": "421283",
"pickupotpStatus": "1",
"empPresentStatus": "0",
"latitdute": "12.9583665",
"longitude": "77.6635659"
},
{
"tripId": "1",
"pickUpLatitidute": "",
"pickUpLongitude": "",
"cabNo": "Ad2K2001",
"driverId": "G2E100",
"routeId": "1",
"tripDate": "2017-08-01 15:45:55",
"startTime": "15:45:55",
"endTime": "14:48:55",
"shiftId": "1",
"tripStatus": "0",
"id": "2",
"empId": "G2E200",
"callStartTime": "",
"callEndTime": "",
"cabReachingTime": "",
"pickupTime": "",
"dropTime": "",
"dropStatus": "0",
"otp": "",
"pickupotpStatus": "0",
"empPresentStatus": "0",
"latitdute": "12.9630167",
"longitude": "77.6268656"
}
]
}

这是我在单击时显示地图的代码。

<!DOCTYPE html>
<html>
<head>
<title>map</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDDsuLejDmtPUTbx6AbVuuH6C2VjZILXnM&libraries=places"></script>
<script type="text/javascript">

</script>

<script type="text/javascript">
var centreGot = false;
var map; // Global declaration of the map
var lat_longs_map = new Array();
var markers_map = new Array();
var iw_map;
iw_map = new google.maps.InfoWindow();

function tester(lat,long) {

var myOptions = {
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP}
map = new google.maps.Map(document.getElementById("map_canvas"), 
myOptions);
// Try W3C Geolocation (Preferred)
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
map.setCenter(new google.maps.LatLng(lat,long));
}, function() { alert("Unable to get your current position. Please try again. Geolocation service failed."); });
// Browser doesn't support Geolocation
}else{
alert('Your browser does not support geolocation.');
}
google.maps.event.addListener(map, "bounds_changed", function(event) {
if (!centreGot) {
var mapCentre = map.getCenter();
marker_0.setOptions({
position: new google.maps.LatLng(lat,long) 
});
}
centreGot = true;
});
var markerOptions = {
map: map    
};
marker_0 = createMarker_map(markerOptions);
google.maps.event.addDomListener(window, "load");
}

function createMarker_map(markerOptions) {
var marker = new google.maps.Marker(markerOptions);
markers_map.push(marker);
lat_longs_map.push(marker.getPosition());
return marker;
}


</script> 
</head>
<body>
<div id="map_canvas" style="width: 100%; height: 350px;">
<button onclick="tester(12.9630167,77.6268656);">My Position</button> </div>
</body>
</html>

在您的情况下,您可以在 ajax 成功时调用相同的函数,例如

$.ajax({
type:'POST',
url:your url,
data:your data,
success:function(res){
var position=res.data;
for (var i=0; i<position.length; i++)
{
tester(position[i].latitude,position[i].longitude);
}
}
});

希望它能奏效。

我不明白你想展示你的观点,你的res.data中有两个对象,每个对象都有pick_up坐标和简单坐标。您一次只能显示一个,在这种情况下,您必须具有pick_up坐标。我做了一些更改。

<!DOCTYPE html>
<html>
<head>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyC7lDrYPDmJz1JsQh2rbWA9uRZHcFk_xJY">
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).on('click','#btn-submit',function(e){

e.preventDefault();
$.ajax({
type:'POST',
url :"getLatLan.php",
data : $('#testForm').serialize(),
success: function(data) {
var res = jQuery.parseJSON(data);//your_res is equal to var res you can delete that.
var your_res={
"status": "success",
"count": 2,
"data": [
{
"tripId": "1",
"pickUpLatitidute": "12.9630167",
"pickUpLongitude": "77.6268656",
"cabNo": "Ad2K2001",
"driverId": "G2E100",
"routeId": "1",
"tripDate": "2017-08-01 15:45:55",
"startTime": "15:45:55",
"endTime": "14:48:55",
"shiftId": "1",
"tripStatus": "0",
"id": "1",
"empId": "G2E201",
"callStartTime": "",
"callEndTime": "",
"cabReachingTime": "",
"pickupTime": "15:50:02",
"dropTime": "",
"dropStatus": "0",
"otp": "421283",
"pickupotpStatus": "1",
"empPresentStatus": "0",
"latitdute": "12.9583665",
"longitude": "77.6635659"
},
{
"tripId": "1",
"pickUpLatitidute": "",
"pickUpLongitude": "",
"cabNo": "Ad2K2001",
"driverId": "G2E100",
"routeId": "1",
"tripDate": "2017-08-01 15:45:55",
"startTime": "15:45:55",
"endTime": "14:48:55",
"shiftId": "1",
"tripStatus": "0",
"id": "2",
"empId": "G2E200",
"callStartTime": "",
"callEndTime": "",
"cabReachingTime": "",
"pickupTime": "",
"dropTime": "",
"dropStatus": "0",
"otp": "",
"pickupotpStatus": "0",
"empPresentStatus": "0",
"latitdute": "12.9630167",
"longitude": "77.6268656"
}
]
};
var myobject=your_res.data;
for(var i=0; i<1; i++)
{
//alert(myobject[i].latitdute+'-'+myobject[i].longitude);
$lati=parseFloat(myobject[i].latitdute);
$long=parseFloat(myobject[i].longitude);
$pic_lati=parseFloat(myobject[i].pickUpLatitidute);
$pic_long=parseFloat(myobject[i].pickUpLongitude);
//alert($lati);
initMap();
}
//console.log(res);
if(res['status']=='success'){
initMap();
}
},
error:function(exception){
alert('Exeption:'+exception);
}
});
});
</script>
<script>
function initMap() {
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 14,
center: {
lat:12.9583665,
lng:77.6635659
} // Starting Point Marathahalli
});
directionsDisplay.setMap(map);
calculateAndDisplayRoute(directionsService, directionsDisplay);
}
function calculateAndDisplayRoute(directionsService, directionsDisplay) {
var selectedMode = document.getElementById('mode').value;
/* configure waypoints */
// var waypts = [];
// waypts.push({
//   location: {
//     lat: 12.9583662,
//     lng: 77.6635653
//   }, // HAL
//   stopover: true
// }, {
//   location: {
//     lat: 12.9630164,
//     lng: 77.6268655
//   },
//   stopover: true
// });
directionsService.route({
origin: {
lat:$lati,
lng:$long
}, // Haight.
destination: {
lat:$pic_lati,
lng:$pic_long
}, // Ending Point Shivaji Nagar.
travelMode: google.maps.TravelMode[selectedMode],
//waypoints: waypts
}, function(response, status) {
if (status == 'OK') {
directionsDisplay.setDirections(response);
console.log(response);
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
</script>
<style>
#map {
height: 100%;
}

/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto', 'sans-serif';
line-height: 30px;
padding-left: 10px;
}
</style>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Travel modes in directions</title>

</head>
<body>
<form id="testForm">
<select name="tripId">
<option value="">Select trip</option>
<option value="1">1</option>
<option value="2">2</option>
</select>
<button type="button" id="btn-submit">submit</button>
</form><br></br>
<div id="floating-panel">
<b>Mode of Travel: </b>
<select id="mode">
<option value="DRIVING">Driving</option>
</select>
</div>
<div id="map"></div>
</body>
</html>

相关内容

  • 没有找到相关文章

最新更新