我正在尝试获取certian城市的天气信息(城市正在动态变化),并且遇到了非常易于集成的地图API。但是一旦我尝试过,即使我给了另一个城市的经纬度,也就是慕尼黑,它只显示了莫斯科。
这是代码:
<html>
<head>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script src="http://openweathermap.org/js/OWM.OpenLayers.1.3.4.js" ></script>
</head>
<body onload="init()">
<div id="basicMap"></div>
</body>
<script type="text/javascript">
function init() {
//Center of map
var lat = 48.24806; // <--- some dynamic location
var lon = 11.90166; //<--- some dynamic location
var lonlat = new OpenLayers.LonLat(lon, lat);
var map = new OpenLayers.Map("basicMap");
// Create overlays
// OSM
var mapnik = new OpenLayers.Layer.OSM();
// Stations
var stations = new OpenLayers.Layer.Vector.OWMStations("Stations");
// Current weather
var city = new OpenLayers.Layer.Vector.OWMWeather("Weather");
//Addind maps
map.addLayers([mapnik, stations, city]);
map.setCenter( lonlat, 10 );
}
</script>
</html>
我只想为我的服务器节省一些加载能量,并在前端使用js解决此天气问题。如果可行,那就太好了,请帮忙。为什么即使给我不同的经度和纬度,我也要坚持在莫斯科。这是api的链接:
http://openweathermap.org/tutorial/openlayers
最佳答案
显然,您需要设置投影以使其正常工作。
这是一个以伦敦为中心的代码示例:
<html>
<head>
<script src="http://openweathermap.org/js/OWM.OpenLayers.1.3.4.js" ></script>
</head>
<body onload="init()">
<div id="basicMap"></div>
</body>
<script type="text/javascript">
function init() {
//Center of map
var lat = 51.5112139; // <--- some dynamic location
var lon = -0.1198244; //<--- some dynamic location
var map = new OpenLayers.Map("basicMap");
var fromProjection = new OpenLayers.Projection("EPSG:4326"); // Transform from WGS 1984
var toProjection = new OpenLayers.Projection("EPSG:900913"); // to Spherical Mercator Projection
var position = new OpenLayers.LonLat(lon, lat).transform( fromProjection, toProjection);
// Create overlays
// OSM
var mapnik = new OpenLayers.Layer.OSM();
// Stations
var stations = new OpenLayers.Layer.Vector.OWMStations("Stations");
// Current weather
var city = new OpenLayers.Layer.Vector.OWMWeather("Weather");
//Addind maps
map.addLayers([mapnik, stations, city]);
map.setCenter( position, 5 );
}
</script>
</html>
要获取您所在位置的经度和纬度,可以使用以下URL:
http://www.mapcoordinates.net/en
希望这可以帮助
关于javascript - OpenWeatherMap- map 仅显示莫斯科,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/17423540/