使用谷歌地图过境信息显示旅行时间

Using google maps transit info to show travel duration

本文关键字:显示 旅行 时间 信息 过境 谷歌地图      更新时间:2023-09-26

我创建了一个地图解决方案,根据距离和乘坐公共交通工具的时间来定位最近的老师。但是我有一个问题循环通过计算旅行持续时间的函数(calculateDuration();)。我没有收到任何错误,但它返回"未定义"。

如何设置我的脚本:

/* 
Json i passed through the API ex.:
{
"status": "success",
"message": "Data selected from database",
"data": [
{
"id": "962",
"status": "Active",
"name": "Name name",
"lat": "55.690606",
"lng": "12.565927",
"subjects": "Subjects....",
"study": "Matematik, Københavns Universitet"
},
*/
(function() {
	window.onload = function() {
		// Setting up vars
		var json = $.getJSON('/api/v1/teachers_by_location', function(data) { 
		var out = data.data; 
		var map = new google.maps.Map(document.getElementById("map"), {
          center: new google.maps.LatLng(55.6764184, 12.569247200000063),
          zoom: 13,
          mapTypeId: google.maps.MapTypeId.ROADMAP
        });
		var infoWindow = new google.maps.InfoWindow();
 		var distanceObj = [], i = 0;
		var directionsDisplay = new google.maps.DirectionsRenderer({map:map});
		var directionsService = new google.maps.DirectionsService;
		// Student marker
		latLng = new google.maps.LatLng(55.6764184, 12.569247200000063);
		var marker = new google.maps.Marker({
			position: latLng,
			map: map,
			animation: google.maps.Animation.BOUNCE,
			title: "Customer"
		});
	    $.each(out, function (a, b) {
			distanceObj[i] = { distance: calculateDistance(55.6764184, 12.569247200000063, b.lng, b.lat), duration: calculateDuration(directionsService, b.lng, b.lat), location: a, name: b.name, subjects: b.subjects, study: b.study };
	        ++i;
	    });
	    distanceObj.sort(function (a, b) {
	        return parseInt(a.distance) - parseInt(b.distance)
	    });
	    $.each(distanceObj, function (a, b) {
	    	$('#list').append('<tr><td>' + b.name + '</td><td>' + b.study + '</td><td>' + b.subjects + '</td><td>' + b.distance + 'm (' + b.duration + ')</td></tr>');
	    });
	    function calculateDistance(meineLongitude, meineLatitude, long1, lat1) {
	        erdRadius = 6371;
	        meineLongitude = meineLongitude * (Math.PI / 180);
	        meineLatitude = meineLatitude * (Math.PI / 180);
	        long1 = long1 * (Math.PI / 180);
	        lat1 = lat1 * (Math.PI / 180);
	        x0 = meineLongitude * erdRadius * Math.cos(meineLatitude);
	        y0 = meineLatitude * erdRadius;
	        x1 = long1 * erdRadius * Math.cos(lat1);
	        y1 = lat1 * erdRadius;
	        dx = x0 - x1;
	        dy = y0 - y1;
	        d = Math.sqrt((dx * dx) + (dy * dy));
	        return Math.round(d * 1000);
	    };
		function calculateDuration(directionsService, long2, lat2) {
		var lat3 = parseFloat(lat2);
		var long3 = parseFloat(long2);
		  directionsService.route({
		    origin: {lat: lat3, lng: long3},
		    destination: {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>},
		    travelMode: google.maps.TravelMode['TRANSIT']
		  }, function(response, status) {
		    if (status == google.maps.DirectionsStatus.OK) {
		      return response.routes[0].legs[0].duration.text;
		    } else {
		      return "Error";
		    }
		  });
		};
		// Looping through the JSON data
		for (var i = 0, length = out.length; i < length; i++) {
			var data = out[i],
			latLng = new google.maps.LatLng(data.lat, data.lng);
			// Creating a marker and putting it on the map
			var marker = new google.maps.Marker({
				position: latLng,
				map: map,
				title: data.name
			});
			// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
			(function(marker, data) {
				// Attaching a click event to the current marker
				google.maps.event.addListener(marker, "click", function(e) {
					infoWindow.setContent(data.name);
					infoWindow.open(map, marker);
				});
			})(marker, data);
		}
		});
	}
})();
		body {
			font-family: helvetica;
		}
		#map { 
			position: absolute;
			right: 0;
			top: 0;
			width: 30%;
			height: 100%; 
		}
		#list_holder { 
			position: absolute;
			left: 0;
			bottom: 0;
			width: 70%;
			height: 100%; 
			overflow-y: scroll;
		}
		#list { 
			position: relative;
			float: left;
			width: 100%;
			height: 100%; 
		}
<script src="http://code.jquery.com/jquery-2.1.4.min.js"></script>
<script src="http://code.jquery.com/jquery-2.1.4.min.js//maps.googleapis.com/maps/api/js?sensor=false"></script>
	<div id="map"></div>
	<div id="list_holder">
		<table id="list" border="1">
			<tr>
				<td colspan="4">Nærmeste undervisere:</td>
			</tr>
		</table>
	</div>

有人能帮我吗?

更新:当这样修改脚本时:

    function calculateDuration(directionsService, long2, lat2) {
    var lat3 = parseFloat(lat2);
    var long3 = parseFloat(long2);
      directionsService.route({
        origin: {lat: lat3, lng: long3},
        destination: {lat: <?php echo $lat; ?>, lng: <?php echo $lng; ?>},
        travelMode: google.maps.TravelMode['TRANSIT']
      }, function(response, status) {
        if (status == google.maps.DirectionsStatus.OK) {
          //return response.routes[0].legs[0].duration.text;
          //console.log("hej");
          console.log(response.routes[0].legs[0].duration.text);
        } else {
          //return "Error";
          console.log("error");
        }
      });
    };

console.logs:

121错误3定时器49分钟。3定时器14分钟。3定时器32分钟。3定时器21分钟。3定时器48分钟。3定时器20分钟。3定时器21分钟。3定时器16分钟。3定时器18分钟。58分钟。

那么为什么当我试图返回文本时未定义?

如指南服务文档所述:

  • duration表示该航段的总持续时间,为Duration下列形式的对象:
    • value表示持续时间,单位为秒。
    • text包含持续时间的字符串表示。

如果持续时间未知,这些字段可能是未定义的

当你得到google.maps.DirectionsStatus.OK时,你的DirectionsResult是好的,试着使用它的一些未定义的部分:)。console.log(JSON.stringify(response));将帮助您了解哪些是。