我正在尝试在点击时向地图添加新标记并尝试保存标题和说明以显示在标记悬停上但是我收到以下错误:
Cannot read property 'add Layer' of undefined
使用Javascript:
<script type="text/javascript">
var map;
function init() {
var map = new OpenLayers.Map('map');
var proj4326 = new OpenLayers.Projection("EPSG:4326");
var projmerc = new OpenLayers.Projection("EPSG:900913");
var layerOSM = new OpenLayers.Layer.OSM("Street Map");
map.addLayers([layerOSM]);
if (!map.getCenter()) map.zoomToMaxExtent();
map.events.register("mousemove", map, function (e) {
var position = this.events.getMousePosition(e);
OpenLayers.Util.getElement("coords").innerHTML = 'MOUSE POSITION ' + position;
var lonlat = map.getLonLatFromPixel(this.events.getMousePosition(e));
//OpenLayers.Util.getElement("lonlatTG").innerHTML = 'lonlat => ' + lonlat;
var lonlatTransf = lonlat.transform(map.getProjectionObject(), proj4326);
//OpenLayers.Util.getElement("lonlatTrans").innerHTML = 'lonlatTransf => ' + lonlatTransf;
//OpenLayers.Util.getElement("lonlatDouble").innerHTML = 'lonlat => ' + lonlat;
document.getElementById("lon").innerHTML = "Longitude: " + lonlatTransf.lon;
document.getElementById("lat").innerHTML = "Latidue : " + lonlatTransf.lat;
});
map.events.register("click", map, function (e) {
var iconT = "http://maps.google.com/mapfiles/ms/icons/red-pushpin.png"; //document.getElementsByName("Icon").value;
var title = document.getElementById("Title").value;
var description = document.getElementById("Description").value;
var position = this.events.getMousePosition(e);
var icon = new OpenLayers.Icon(iconT);
var lonlat = map.getLonLatFromPixel(position);
var lonlatTransf = lonlat.transform(map.getProjectionObject(), proj4326);
var longitude = lonlatTransf.lon;
var latitude = lonlatTransf.lat;
var lonlat = lonlatTransf.transform(proj4326, map.getProjectionObject());
/*var markerslayer = new OpenLayers.Layer.Markers("Markers");*/
$.ajax({
type: 'POST',
data: { 'desc': description, 'title': title, 'icon': iconT, 'lon': longitude, 'lat': latitude },
url: '@Url.Action("Test")',
success: function () {
alert('Your Marker was saved successfully!');
addMarker(title, description, longitude, latitude);
/* markerslayer.addMarker(new OpenLayers.Marker(lonlat, icon));
map.addLayer(markerslayer);*/
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError.toString());
}
});
});
/*map.addControl(new OpenLayers.Control.LayerSwitcher());*/
}
function addMarker(title,description,lon,lat){
var markerslayer = new OpenLayers.Layer.Markers("Markers");
map.addLayer(markerLayer);
lonLat = new OpenLayers.LonLat(lon,lat);
marker = new OpenLayers.Marker(lonLat);
markerLayer.addMarker(marker);
marker.icon.imageDiv.title = title; //is this correct way to add title? How can I description too?
}
</script>
答案 0 :(得分:2)
您的map变量是init函数的本地变量:
<script type="text/javascript">
var map;
function init() {
var map = new OpenLayers.Map('map');
删除“var”:
var map;
function init() {
map = new OpenLayers.Map('map');