我是Javascript的新手,但是我需要它在我的项目中使用googlemaps,我试图为每个特定城市设置纬度,经度和地图缩放的值,所以我从隐藏的表单输入获取城市名称使用Switch切换城市名称。
cityDiv = document.getElementById('id_city');
cityDiv.value = idCity ;
switch (idCity)
{
case "city1":
var map_long = 31.37667;
var map_lat = 31.04306;
var map_zoom = 3;
break
case "city2":
var map_long = 31.33333;
var map_lat = 29.85;
var map_zoom = 7;
break
default:
var map_long = 31.37667;
var map_lat = 31.04306;
var map_zoom = 3;
}
function onLoad() {
map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.centerAndZoom(new GLatLng(map_lat,map_long) , map_zoom);
GEvent.addListener(map, 'click', function(overlay, point) {
if (prev_pin) {
map.removeOverlay(prev_pin);
prev_pin = null;
}
//var yPoint = new YGeoPoint({{ place.latitude }},{{ place.longitude }});
if (point) {
pin = new GMarker(point);
map.addOverlay(pin);
prev_pin = pin;
latDiv = document.getElementById('id_latitude');
lngDiv = document.getElementById('id_longitude');
lngDiv.value = point.x;
latDiv.value = point.y;
}
});
}
抱歉这个新手问题。
最好的问候。
来自geowa4评论的编辑:
问题和问题是变量永远不会设置:(,所以我的代码有什么问题?!我将“cityDiv.value = idCity;”更改为“var idCity = cityDiv.value;”这不起作用好吧,但这次地图拒绝加载
答案 0 :(得分:3)
尝试以下代码:
mapInfo =
{
"city1":
{
"long": 31.37667,
"lat": 31.04306,
"zoom": 3
},
"city2":
{
"long": 31.33333,
"lat": 29.85,
"zoom": 7
}
};
function onLoad() {
map = new GMap(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var cityDiv = document.getElementById('id_city');
var idCity = cityDiv.value || "city1";
map.centerAndZoom(new GLatLng(mapInfo[idCity].lat,mapInfo[idCity].long) , mapInfo[idCity].zoom);
GEvent.addListener(map, 'click', function(overlay, point) {
if (prev_pin) {
map.removeOverlay(prev_pin);
prev_pin = null;
}
//var yPoint = new YGeoPoint({{ place.latitude }},{{ place.longitude }});
if (point) {
pin = new GMarker(point);
map.addOverlay(pin);
prev_pin = pin;
latDiv = document.getElementById('id_latitude');
lngDiv = document.getElementById('id_longitude');
lngDiv.value = point.x;
latDiv.value = point.y;
}
});
}
答案 1 :(得分:2)
您是否尝试过转储值,逐步调试? Alert statements或console.log()
语句,以查看该页面认为该选择的值是什么?
您也可以考虑制作一个对象,然后可以更新:
// Untested, but you should get the gist
var cityInfo = {
map_long : 0.0,
map_lat : 0.0,
map_zoom : 0
};
switch (idCity) {
case "city1":
cityInfo.map_long = 31.37667;
cityInfo.map_lat = 31.04306;
cityInfo.map_zoom = 3;
break
case "city2":
cityInfo.map_long = 31.33333;
cityInfo.map_lat = 29.85;
cityInfo.map_zoom = 7;
break
default:
cityInfo.map_long = 31.37667;
cityInfo.map_lat = 31.04306;
cityInfo.map_zoom = 3;
}
答案 2 :(得分:1)
你的问题是范围,纯粹和简单。使用var
将变量范围限定为当前词法范围,在var map_long = 31.37667;
等的情况下是switch语句。一旦超出该范围,除非保留外部引用,否则在该范围内声明的任何变量都将消失。您可以删除var
语句,但这会使变量成为全局变量。我建议在一个对你有意义的范围内声明你的变量,只有在绝对必要时才将它们设为全局变量。