OpenWeatherMap - map is showing only moscow - javascript

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

Related

OpenLayers map.addLayer TypeError

I'm trying to do some simple drawing on OpenStreetMap data using OpenLayers (version 6.5.0). The map loads fine. I try to do the drawing when the button in the top right is clicked.
I convert this array of GPS coordinates into a Polygon, into a Feature, into an ol.source.Vector, into an ol.layer.Vector. I log every object constructed along the way on the console. This appears to go fine.
I finally want to add the (Vector) layer to the existing map using the .addLayer() function.
At this point, things go wrong inside the OpenLayer 6.5.0 JavaScript code. Deep inside the ol.js code, it throws a TypeError: t.addEventListener is not a function.
Browser screenshot
I've looked at multiple examples:
https://openlayers.org/en/latest/examples/polygon-styles.html
https://openlayers.org/en/latest/examples/geojson.html
So far, I have no clue whether this a bug in OpenLayer 6.5.0 or I'm missing something during conversion of my GPS coordinates array into an ol.layer.vector object. Any hints on this?
Entire html/javascript code below:
<meta charset="UTF-8">
<html>
<head>
<title>OSM test</title>
<link rel="stylesheet" href="ol.css">
<script src="ol.js"></script>
<script type="text/javascript">
function loadMap(domDivId, szLat, szLon, zoom) {
var vView = new ol.View({
center: ol.proj.fromLonLat([szLon, szLat]),
zoom: zoom
});
var lTile = new ol.layer.Tile({
source: new ol.source.OSM()
})
var map = new ol.Map({
target: domDivId,
layers: [lTile],
view: vView
});
return map;
}
function drawBermuda(map) {
// Bermuda triangle (approximate) GPS coordinates in [lat,lon] format
var arPath = [
[18.472282,-66.123934], // Bermuda
[32.297504,-64.778447], // Puerto Rico
[25.732447,-80.133221], // Miami
[18.472282,-66.123934] // Bermuda
];
console.log(arPath);
var pPath = {
'type': 'Polygon',
'coordinates': arPath
};
console.log(pPath);
var fPath = {
'type': 'Feature',
'geometry': pPath
};
console.log(fPath);
var svPath = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(fPath)
});
console.log(svPath);
var lvPath = new ol.layer.Vector({
source: svPath,
});
console.log(lvPath);
map.addLayer([lvPath]);
}
</script>
</head>
<body>
<div id="div_map" style="width:100%; height:100%; position:absolute; left:0px; top:0px; margin:0px; padding;0px; z-index:-10"></div>
<script>
map = loadMap('div_map', 25.0, -71.0, 5);
</script>
<div style="float:right">
<button onclick="drawBermuda(map);" style="height:100;width:100px;">click me please :-)</button>
</div>
</body>
</html>
P.S. I am aware that I still may have to swap latitude and longitude and convert the coordinates in some other way for OpenLayer to interpret them correctly. But that's not the main point here. I guess...
As well as missing and misplaced [ ] geojson coordinates must be specified in lon, lat order and features must be read into the view projection
<meta charset="UTF-8">
<html>
<head>
<title>OSM test</title>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/css/ol.css" type="text/css">
<script src="https://cdn.jsdelivr.net/gh/openlayers/openlayers.github.io#master/en/v6.5.0/build/ol.js"></script>
<script type="text/javascript">
function loadMap(domDivId, szLat, szLon, zoom) {
var vView = new ol.View({
center: ol.proj.fromLonLat([szLon, szLat]),
zoom: zoom
});
var lTile = new ol.layer.Tile({
source: new ol.source.OSM()
})
var map = new ol.Map({
target: domDivId,
layers: [lTile],
view: vView
});
return map;
}
function drawBermuda(map) {
// Bermuda triangle (approximate) GPS coordinates in [lon,lat] format
var arPath = [[
[-66.123934, 18.472282], // Bermuda
[-64.778447, 32.297504], // Puerto Rico
[-80.133221, 25.732447], // Miami
[-66.123934, 18.472282] // Bermuda
]];
var pPath = {
'type': 'Polygon',
'coordinates': arPath
};
var fPath = {
'type': 'Feature',
'geometry': pPath
};
var svPath = new ol.source.Vector({
features: new ol.format.GeoJSON().readFeatures(fPath, {featureProjection: map.getView().getProjection()})
});
var lvPath = new ol.layer.Vector({
source: svPath,
});
map.addLayer(lvPath);
}
</script>
</head>
<body>
<div id="div_map" style="width:100%; height:100%; position:absolute; left:0px; top:0px; margin:0px; padding;0px; z-index:-10"></div>
<script>
map = loadMap('div_map', 25.0, -71.0, 5);
</script>
<div style="float:right">
<button onclick="drawBermuda(map);" style="height:100;width:100px;">click me please :-)</button>
</div>
</body>
</html>

importe markers from database usin HERE MAPS API

Iam trying to use HERE MAPS API, and i want to get markers from mySQL database, i am using the api like showing in here forume but markers doesnt shown im the map, i ma using this code :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<link rel="stylesheet" type="text/css" href="https://js.api.here.com/v3/3.0/mapsjs-ui.css?dp-version=1542186754" />
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-core.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-service.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-ui.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-mapevents.js"></script>
<script type="text/javascript" src="https://js.api.here.com/v3/3.0/mapsjs-clustering.js"></script>
</head>
<body>
<div id="map" style="width: 100%; height: 400px; background: grey" />
<script type="text/javascript" charset="UTF-8" >
/**
* Display clustered markers on a map
*
* Note that the maps clustering module http://js.api.here.com/v3/3.0/mapsjs-clustering.js
* must be loaded to use the Clustering
* #param {H.Map} map A HERE Map instance within the application
* #param {Array.<Object>} data Raw data that contains airports' coordinates
*/
function startClustering(map, data) {
// First we need to create an array of DataPoint objects,
// for the ClusterProvider
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.latitude, item.longitude);
});
// Create a clustering provider with custom options for clusterizing the input
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
// Maximum radius of the neighbourhood
eps: 32,
// minimum weight of points required to form a cluster
minWeight: 2
}
});
// Create a layer tha will consume objects from our clustering provider
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
// To make objects from clustering provder visible,
// we need to add our layer to the map
map.addLayer(clusteringLayer);
}
/**
* Boilerplate map initialization code starts below:
*/
// Step 1: initialize communication with the platform
var platform = new H.service.Platform({
app_id: 'devportal-demo-20180625',
app_code: '9v2BkviRwi9Ot26kp2IysQ',
useHTTPS: true
});
var pixelRatio = window.devicePixelRatio || 1;
var defaultLayers = platform.createDefaultLayers({
tileSize: pixelRatio === 1 ? 256 : 512,
ppi: pixelRatio === 1 ? undefined : 320
});
// Step 2: initialize a map
var map = new H.Map(document.getElementById('map'), defaultLayers.normal.map, {
center: new H.geo.Point(30.789, 33.790),
zoom: 2,
pixelRatio: pixelRatio
});
// Step 3: make the map interactive
// MapEvents enables the event system
// Behavior implements default interactions for pan/zoom (also on mobile touch environments)
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// Step 4: create the default UI component, for displaying bubbles
var ui = H.ui.UI.createDefault(map, defaultLayers);
// Step 5: request a data about airports's coordinates
var url= 'https://jsondataexemple.com/hereapi/jsondata.json';
$.ajax({
type: 'GET',
dataType: 'json',
url: url,
success: function (data) {
startClustering(map, data);
}
});
</script>
</body>
</html>
the Json file is generated from my database by a php script :
[{"id":2812,"latitude":"33.5706476858027","longitude":"-7.600212045766735"},{"id":2811,"latitude":"33.56960668831451","longitude":"-7.6025319565980904"}]
thanks for helping me
In your json, latitude, longitude seems to be String. they should Float.
you may consider using ParseFloat in JS or change your php script.
after testing chrome debuger i found that the probleme is from my local host, but the code work properly in my online host !.
sorry

Bias location returns on Google Places API autocomplete

I am using the Google places API to autocomplete street address searches. I want to bias the results to a 50 mile radius around a specific longitude and latitude (this is a fixed location, it doesn't depend on the user). Currently, it autocompletes addresses, but it doesn't bias them based on location (other than doing within the U.S.). Specifically, I want to bias a 300 mile radius around latitude: 34.159947, longitude: -118.257017.
<script src="https://maps.googleapis.com/maps/api/js?sensor=false&libraries=places"></script>
...
<input id="address-search" type="text" value="" name="subject">
$(document).ready(function() {
var input = document.getElementById('address-input');
var options = {componentRestrictions: {country: 'us'} };
new google.maps.places.Autocomplete(input, options);
google.maps.event.addDomListener(window, 'load', initialize);
});
       
You can't give it a radius, but you can give it rectangular bounds
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631)
);
var options = {bounds: defaultBounds };
See the Places Autocomplete documentation

How to parse xml file for marker locations and plot on map

I am trying to read points from an xml file rather than from javascript as in the example below.
https://google-developers.appspot.com/maps/documentation/javascript/examples/marker-animations-iteration
But it is not working for me. I have created an xml file containing:
<?xml version="1.0" encoding="UTF-8"?>
<companies>
<company>
<lat>52.511467</lat>
<lng>13.447179</lng>
</company>
<company>
<lat>52.549061</lat>
<lng>13.422975</lng>
</company>
<company>
<lat>52.497622</lat>
<lng>13.396110</lng>
</company>
<company>
<lat>52.517683</lat>
<lng>13.394393</lng>
</company>
</companies>
But I cannot get the points displaying on google maps v3. Does anyone have an example of parsing an xml file for coordinates and then displaying them on a map?
Brilliant - thanks a lot for the hint!
One little mistake is still in the above code:
replace
markers.setMap(map);
by
marker.setMap(map);
...then it'll work!
I use jQuery both to get the XML file and then to parse it. I've used this approach many times but don't have time to test this, so there may be syntax errors.
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
...
var map;
function init()
{
map = new google.maps.Map("map_canvas");
jQuery.get("companies.xml", {}, function(data) {
jQuery(data).find("company").each(function() {
var company = jQuery(this);
var lat = jQuery(company).find("lat").text();
var lon = jQuery(company).find("lng").text();
var latlng = new google.maps.LatLng( parseFloat(lat), parseFloat(lon) );
var marker = new google.maps.Marker( { position: latlng, });
markers.setMap(map);
});
});
}

How do I add Google Maps on my site?

I have a form and I want to add a "select location" option.
How can I do this, and how can I place a pin as the selected location?
You may want to consider using the Google Maps API, as davek already suggested.
The following example may help you getting started. All you would need to do is to change the JavaScript variable userLocation with the location chosen by your users from the drop-down field you mention.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark)
{
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
The above example would render a map like the one below:
The map will not show if the Google Client-side Geocoder cannot retreive the coordinates from the address.
Check out the Google Maps API. There's lots of information there and several examples:without knowing more about your environment/requirements it is difficult to be more specific.

Categories

Resources