gpt4 book ai didi

javascript - OpenWeatherMap - map 仅显示莫斯科

转载 作者:行者123 更新时间:2023-11-28 02:08:41 26 4
gpt4 key购买 nike

我正在尝试获取某些城市的天气信息(城市是动态变化的),我发现了这个 map 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com