使用javascript在谷歌道路API中设置开始和结束位置
Posted
技术标签:
【中文标题】使用javascript在谷歌道路API中设置开始和结束位置【英文标题】:set start and end position in google roads API using javascript 【发布时间】:2015-11-03 09:33:35 【问题描述】:我想知道在我通过谷歌道路 API 检索坐标和 placeId 时是否可以在地图中设置开始和结束位置?因为当我通过设置自定义坐标来初始化 Roads API 时:
var mapOptions =
zoom: 17,
center: lat: -33.8667, lng: 151.1955
;
它向我显示了地图中存在坐标的特定位置。但我想初始化一张地图,在地图中设置起点和终点位置,然后开始使用 snapToRoads API 检索坐标。
【问题讨论】:
【参考方案1】:好的,我自己挖了一点,自己解决了。
javascript 部分:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?libraries=drawing,places"></script>
<!--Elevation JS
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>-->
<script>
//GOOGLE_API_KEY
var apiKey = 'GOOGLE_API_KEY';
alert("Provide GOOGLE API KEY");
var map;
var elevator;
var directionsDisplay;
var directionsService;
var drawingManager;
var placeIdArray = [];
var polylines = [];
var snappedCoordinates = [];
var initialLocation;
var siberia = new google.maps.LatLng(60, 105);
var newyork = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var browserSupportFlag = new Boolean();
function initialize()
var mapOptions =
zoom: 17,
center: lat: -33.8667, lng: 151.1955
;
directionsService = new google.maps.DirectionsService();
var polylineOptionsActual = new google.maps.Polyline(
strokeColor: '#FF0000',
strokeOpacity: 0.6,
strokeWeight: 2
);
directionsDisplay = new google.maps.DirectionsRenderer(polylineOptions: polylineOptionsActual);
map = new google.maps.Map(document.getElementById('map'), mapOptions);
directionsDisplay.setMap(map);
// Create an ElevationService
elevator = new google.maps.ElevationService();
// Adds a Places search box. Searching for a place will center the map on that
// location.
map.controls[google.maps.ControlPosition.RIGHT_TOP].push(
document.getElementById('bar'));
var autocomplete = new google.maps.places.Autocomplete(document.getElementById('autocStart'));
autocomplete.bindTo('bounds', map);
autocomplete.addListener('place_changed', function()
var placeStart = autocomplete.getPlace();
//alert(placeStart.place_id);
document.getElementById("startPlaceId").value=placeStart.place_id;
);
var autocomplete1 = new google.maps.places.Autocomplete(document.getElementById('autocEnd'));
autocomplete1.bindTo('bounds', map);
autocomplete1.addListener('place_changed', function()
var placeEnd = autocomplete1.getPlace();
//alert(placeEnd.place_id);
document.getElementById("endPlaceId").value=placeEnd.place_id;
);
// Enables the polyline drawing control. Click on the map to start drawing a
// polyline. Each click will add a new vertice. Double-click to stop drawing.
drawingManager = new google.maps.drawing.DrawingManager(
drawingMode: google.maps.drawing.OverlayType.POLYLINE,
drawingControl: true,
drawingControlOptions:
position: google.maps.ControlPosition.TOP_CENTER,
drawingModes: [
google.maps.drawing.OverlayType.POLYLINE
]
,
polylineOptions:
strokeColor: '#696969',
strokeWeight: 2
);
drawingManager.setMap(map);
// Snap-to-road when the polyline is completed.
drawingManager.addListener('polylinecomplete', function(poly)
var path = poly.getPath();
polylines.push(poly);
placeIdArray = [];
runSnapToRoad(path);
);
// Clear button. Click to remove all polylines.
$('#clear').click(function(ev)
for (var i = 0; i < polylines.length; ++i)
polylines[i].setMap(null);
polylines = [];
ev.preventDefault();
return false;
);
// Snap a user-created polyline to roads and draw the snapped path
function runSnapToRoad(path)
var pathValues = [];
for (var i = 0; i < path.getLength(); i++)
pathValues.push(path.getAt(i).toUrlValue());
$.get('https://roads.googleapis.com/v1/snapToRoads',
interpolate: true,
key: apiKey,
path: pathValues.join('|')
, function(data)
processSnapToRoadResponse(data);
drawSnappedPolyline();
//getAndDrawSpeedLimits();
);
// Store snapped polyline returned by the snap-to-road method.
function processSnapToRoadResponse(data)
snappedCoordinates = [];
placeIdArray = [];
for (var i = 0; i < data.snappedPoints.length; i++)
var latlng = new google.maps.LatLng(
data.snappedPoints[i].location.latitude,
data.snappedPoints[i].location.longitude);
//getElevation(latlng);
snappedCoordinates.push(latlng);
placeIdArray.push(data.snappedPoints[i].placeId);
//get Altitude in meters
getElevation(snappedCoordinates);
document.getElementById("snappedCoordinatesArray").value=snappedCoordinates;
document.getElementById("snappedPaceIdArray").value=placeIdArray;
// Draws the snapped polyline (after processing snap-to-road response).
function drawSnappedPolyline()
var snappedPolyline = new google.maps.Polyline(
path: snappedCoordinates,
strokeColor: 'black',
strokeWeight: 3
);
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
// Gets speed limits (for 100 segments at a time) and draws a polyline
// color-coded by speed limit. Must be called after processing snap-to-road
// response.
function getAndDrawSpeedLimits()
for (var i = 0; i <= placeIdArray.length / 100; i++)
// Ensure that no query exceeds the max 100 placeID limit.
var start = i * 100;
var end = Math.min((i + 1) * 100 - 1, placeIdArray.length);
drawSpeedLimits(start, end);
// Gets speed limits for a 100-segment path and draws a polyline color-coded by
// speed limit. Must be called after processing snap-to-road response.
function drawSpeedLimits(start, end)
var placeIdQuery = '';
for (var i = start; i < end; i++)
placeIdQuery += '&placeId=' + placeIdArray[i];
$.get('https://roads.googleapis.com/v1/speedLimits',
'key=' + apiKey + placeIdQuery,
function(speedData)
processSpeedLimitResponse(speedData, start);
);
// Draw a polyline segment (up to 100 road segments) color-coded by speed limit.
function processSpeedLimitResponse(speedData, start)
var end = start + speedData.speedLimits.length;
for (var i = 0; i < speedData.speedLimits.length - 1; i++)
var speedLimit = speedData.speedLimits[i].speedLimit;
var color = getColorForSpeed(speedLimit);
// Take two points for a single-segment polyline.
var coords = snappedCoordinates.slice(start + i, start + i + 2);
var snappedPolyline = new google.maps.Polyline(
path: coords,
strokeColor: color,
strokeWeight: 6
);
snappedPolyline.setMap(map);
polylines.push(snappedPolyline);
//passDataToObjC();
function getColorForSpeed(speed_kph)
if (speed_kph <= 40)
return 'purple';
if (speed_kph <= 50)
return 'blue';
if (speed_kph <= 60)
return 'green';
if (speed_kph <= 80)
return 'yellow';
if (speed_kph <= 100)
return 'orange';
return 'red';
function getElevation(snappedCoordinatesArr)
var locations = [];
// Retrieve the latlng and push it on the array
for (var i = 0; i < snappedCoordinatesArr.length; i++)
locations.push(snappedCoordinatesArr[i]);
// Create a LocationElevationRequest object using the array's one value
var positionalRequest =
'locations': locations
//alert(positionalRequest);
// Initiate the location request
elevator.getElevationForLocations(positionalRequest, function(results, status)
if (status == google.maps.ElevationStatus.OK)
// Retrieve the first result
if (results)
var altitudeArr=[];
for(var j=0;j<results.length;j++)
altitudeArr.push(results[j].elevation);
document.getElementById("altitudeArray").value=altitudeArr;
document.getElementById("dataDisplay").style.display="block";
//alert(altitudeArr);
else
alert('No results found');
else
alert('Elevation service failed due to: ' + status);
);
function calcRoute()
var start = document.getElementById("autocStart").value;
var end = document.getElementById('autocEnd').value;
//alert(start);
var request =
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
;
directionsService.route(request, function(response, status)
if (status == google.maps.DirectionsStatus.OK)
directionsDisplay.setDirections(response);
);
$(window).load(initialize);
</script>
还有 html:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Roads API</title>
<style>
html, body, #map
height: 100%;
margin: 0px;
padding: 0px
#panel
position: absolute;
top: 5px;
left: 50%;
margin-left: -180px;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
#bar
width: 240px;
background-color: rgba(255, 255, 255, 0.75);
margin: 8px;
padding: 4px;
border-radius: 4px;
#autoc
width: 98%;
box-sizing: border-box;
</style>
<body>
<div id="map"></div>
<div id="bar">
<form id="geodata-form" action="http://wayzme.sulavmart.com/map/savedata">
<div id="dataDisplay" style="display:none;">
CoordinatesArray:
<input type="text" id="snappedCoordinatesArray" />
AltitudeArray:
<input type="text" id="altitudeArray" />
PaceIdArray:
<input type="text" id="snappedPaceIdArray" />
<input type="hidden" id="startPlaceId" />
<input type="hidden" id="endPlaceId" />
</div>
<p class="auto">
<input type="text" id="autocStart" style="width:98% !important" name="start" />
</p>
<p class="auto">
<input type="text" id="autocEnd" style="width:98% !important" name="end"/>
</p>
<input type="button" value="Get Directions" onClick="calcRoute();">
</form>
<p><a id="clear" href="#">Click here</a> to clear map.</p>
</div>
</body>
</html>
【讨论】:
以上是关于使用javascript在谷歌道路API中设置开始和结束位置的主要内容,如果未能解决你的问题,请参考以下文章
如何删除不相关的道路并在谷歌地图中显示所需的路线?对应的API是啥?