문제

I am trying to get the weather information for a certian cities(cities are coming dynamically) and i came across this map api which is very easy to integrate. but once i tried it, it is showing only moscow even if i gave the lat and lon of another city, say, munich.

this is the code:

<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>

i just want to save some loading energy for my server and do this weather issue in frontend with js. if this would work, it would be wonderful, please help if you can. why am i stuck to moscow here even if give different lat and lons. this is the link for api: http://openweathermap.org/tutorial/openlayers

도움이 되었습니까?

해결책

Apparently you need to set the Projection for it to work correctly.

Here is an example of the code centering at London:

<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>

To get the Longitude and Latitude of your place, you can use this URL: http://www.mapcoordinates.net/en

Hope this helps

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top