我想输入来源和目的地,然后接受地显示来源和目的地之间的方向,但是问题是google.maps.LatLng()
此函数未将变量作为参数。
如果我传递价值,那就行得通
例如:
google.maps.LatLng(35.653341, -97.470570)
................................................... >
我尝试更改数据类型var d
例如:
var d=document.getElementById("destlat").value;
它不起作用
我也尝试过
google.maps.LatLng('arr[a]', 'arr[b]');
它也不起作用
function initMap() {
alert("WELCOME");
var a=document.getElementById("sourcelon").value;
var b=document.getElementById("sourcelat").value;
var c=document.getElementById("destlon").value;
var d=document.getElementById("destlat").value;
var arr=[a,b,c,d,];
alert(arr);
var pointA = new google.maps.LatLng(arr[a], arr[b]);
var pointB = new google.maps.LatLng(arr[c], arr[d]);
var myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "Source",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "Destination",
map: map
});
我想动态传递经度和纬度以起作用,但是它不起作用
答案 0 :(得分:0)
您的代码中有错别字。 pointA
(和pointB
)应为
new google.maps.LatLng(b, a); // lat/lng
(注意不是来自数组)或
new google.maps.LatLng(arr[1], arr[0]); // lat/lng
不是:
var pointA = new google.maps.LatLng(arr[a], arr[b]);
代码段:
function initMap() {
var a = document.getElementById("sourcelon").value;
var b = document.getElementById("sourcelat").value;
var c = document.getElementById("destlon").value;
var d = document.getElementById("destlat").value;
var arr = [a, b, c, d, ];
var pointA = new google.maps.LatLng(arr[1], arr[0]);
var pointB = new google.maps.LatLng(arr[3], arr[2]);
var myOptions = {
zoom: 7,
center: pointA
},
map = new google.maps.Map(document.getElementById('map-canvas'), myOptions),
// Instantiate a directions service.
directionsService = new google.maps.DirectionsService,
directionsDisplay = new google.maps.DirectionsRenderer({
map: map
}),
markerA = new google.maps.Marker({
position: pointA,
title: "point A",
label: "Source",
map: map
}),
markerB = new google.maps.Marker({
position: pointB,
title: "point B",
label: "Destination",
map: map
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map-canvas {
height: 90%;
margin: 0;
padding: 0;
}
<!--
New York, NY, USA (40.7127753, -74.0059728)
Newark, NJ, USA (40.735657, -74.1723667)
-->
<input id="sourcelat" value="40.7127753" size="10" />
<input id="sourcelon" value="-74.0059728" size="10" />
<input id="destlat" value="40.735657" size="10" />
<input id="destlon" value="-74.1723667" size="10" />
<div id="map-canvas"></div>
<!-- Replace the value of the key parameter with your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initMap"></script>