我有一個init()函數,它可以在加載html正文時爲地圖創建一個圖像疊加層。在函數內創建mapOverlay變量。它基本上是「Add overview window to map」下的功能:http://www.ordnancesurvey.co.uk/business-and-government/products/os-openspace/api/code-playground.html(Ordnance Survey是英國的測繪機構,它使用他們的測繪工具)。訪問功能以外的JavaScript變量
現在我想使用html下拉菜單來更改圖像疊加層。如何訪問原始mapOverlay變量以更改其中的某些值?
下面是一些我希望能夠證明問題的示例代碼。
<!DOCTYPE html>
<html>
<head>
<meta charset='utf-8'>
<title>Testing OS OpenSpace</title>
<script type="text/javascript"
src="http://openspace.ordnancesurvey.co.uk/osmapapi/openspace.js?key=BA08531D8339984EE0405F0AC86026A9";>
</script>
<script type="text/javascript">
// Define the osMap variable
var osMap;
// This function creates the map and is called by the div in the HTML
function init()
{
// Create new map
osMap = new OpenSpace.Map('map');
// Define image overlay with URL
var mapOverlay = new OpenSpace.Layer.MapOverlay("logo");
mapOverlay.setHTML('<img src="Image1.jpg" style="width: 100%; height: 100%; opacity: 0.8;"/>');
mapOverlay.setPosition(new OpenLayers.LonLat(391500, 805000));
mapOverlay.setSize(new OpenLayers.Size(3700, 4000));
osMap.addLayer(mapOverlay);
// Set map centre in National Grid Eastings and Northings and select zoom level 4
osMap.setCenter(new OpenSpace.MapPoint(393000, 807000), 6);
// Set the mapOverlay as a document property, so that it can be changed.
}
// This function changes the image, or I'd like it to.
function ChangeImage()
{
// Get the choice from the dropdown. this bit works.
var Choice_ = document.getElementById('Choice');
var Choice = Choice_.options[Choice_.selectedIndex].value;
// Edit the mapOverlay, not sure how to achieve this part.
mapOverlay.setHTML('<img src="$Choice" style="width: 100%; height: 100%; opacity: 0.8;"/>');
}
</script>
<style>
html, body {height: 100%;}
#map {width: 700px; height: 500px; border:1px solid black;}
</style>
</head>
<body onload="init()" id='Body'>
<!-- The div below holds the map -->
<div id="map"></div>
<!-- Now some options for which datasets to display. -->
<td><select id='Choice' onchange="ChangeImage()">
<option value="Image1.jpg" selected="selected">1</option>
<option value="Image2.jpg">2</option>
</select>
</td>
</body>
</html>
那麼,我希望做到的,是得到從init()函數的mapOverlay變量,並利用它在ChangeImage()函數。這是可行的嗎?也許這受OS開放空間API的性質限制,在這種情況下,我最好在他們的社區頁面上提問。但我希望類似這樣的情況在JavaScript中可能會經常出現,以至於查詢可能需要更廣泛的討論。
你能不能簡單地宣佈了var mapOverlay全球,高達旁邊osMap?然後,它將對ChangeImage()可見。 (保持mapOverlay初始化爲init()) – rob