I've imported some JSON data to my console and I'm trying to display a small amount of it to the document. This is an example of the data I have:
{"hours":[{"airTemperature":[{"source":"sg","value":14.03},{"source":"noaa","value":8.06},{"source":"dwd","value":14.03}],"time":"2018-09-29T00:00:00+00:00","waveHeight":[{"source":"sg","value":0.44},{"source":"meto","value":1.28},{"source":"meteo","value":0.44},{"source":"noaa","value":0.78},{"source":"dwd","value":0.63}]},{"airTemperature":[{"source":"sg","value":13.61},{"source":"noaa","value":8.12},{"source
The data is linked to markers I have on a map and I am trying to get some of the data into a text area I have setup in my html file. for example I want to iterate through the data and get all the values from the noaa for both the airTemp and the waveHeight every sixth hour. Although I know I need a loop to do this I've hit a bit of a brick wall as far as my skills are concerned and struggling to find a reference anywhere that I can make sense of. Any pointers in the right direction are greatly appreciated. Here is my js so far:
// create locations coordinates offshore close to named town to get marine information for that area.
var locations = [
["Penzance", 50.070092, -5.767671],
["St Ives", 50.250562, -5.491298],
["Newquay", 50.440782, -5.126195],
["Bude", 50.802900, -4.614876],
["Woolacombe", 51.166777, -4.344528]
];
//set parameters for api information we need
const params = 'waveHeight,airTemperature';
//initiate map
function initMap() {
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 9,
center: { lat: 50.738, lng: -4.002 }
});
// Info Window initialize
var infoWindow = new google.maps.InfoWindow(),
marker, i;
// marker icon
var image = 'https://developers.google.com/maps/documentation/javascript/examples/full/images/beachflag.png';
//set markers on map
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: { lat: locations[i][1], lng: locations[i][2] },
map: map,
title: locations[i][0],
icon: image
});
// gets relevant api data when offshore marker is clicked
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
fetch(`https://api.stormglass.io/point?lat=${locations[i][1]}&lng=${locations[i][2]}¶ms=${params}`, {
headers: {
'Authorization': 'MY_ACCESS_KEY'
}
}).then(function(response) {
return response.json();
}).then(function(data) {
console.log(data);
document.getElementById("waves").innerHTML = data;
});
infoWindow.setContent(locations[i][0]);
infoWindow.open(map, marker);
};
})(marker, i));
}
}
initMap();
Related
So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.
this is what i have so far. but i cant seem to pull the URLS through.. into different markers.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -39.3642, lng: 164.0444318}
});
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -37.7862985, lng: 175.2773836},
{lat: -37.8011434, lng: 174.871265}
]
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;
});
The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function(){
window.location.href = this.url;
});
return marker;
});
Using the Google Maps API with the places library I am able to show nearby schools using the recommended method shown here.
var map;
var infowindow;
function initMap() {
var pyrmont = {lat: -33.867, lng: 151.195};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
type: ['store']
}, callback);
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Here's a working fiddle: https://jsfiddle.net/api/post/library/pure/
The problem is that if I also want to show nearby stores as well as schools, everyone seems to recommend simply doing this:
type: ['store', 'school']
While this technically works, the problem is the map just shows a bunch of meaningless default markers with no way of knowing what it what.
So my question is: How can I change the icon for the schools and stores? Ideally I would show a different icon for each different type.
It's no different than adding custom marker in regular map.Only thing is that you need to make api calls separately for each type.So even type: ['store', 'school'] would work and you get results but there is no type specifier in the results to tell whether it's a school or shop .Also you would need to create their separate callbacks for setting their separate icons
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
icon:"http://example.com/icon.png", //<-- only this line is enough for icon
map: map,
position: place.geometry.location
});
go through this for a better understanding
Moreover every result will have a default icon (as icon property), that can also be used
var marker = new google.maps.Marker({
icon:place.icon,
map: map,
position: place.geometry.location
});
I am getting latitude & longitude from database table and trying to display markers on ajax success. I am getting latitude & longitude on json format but when tried with loop, markers are not displaying.
My JSON Data:
[
{"latitude":"23.046100780353495","longitude":"72.56860542227514"},
{"latitude":"23.088427701737665","longitude":"72.49273109366186"},
{"latitude":"23.061264193197644","longitude":"72.68224525381811"},
{"latitude":"22.977212139977677","longitude":"72.52191352774389"},
{"latitude":"23.002180435752084","longitude":"72.47590827872045"},
{"latitude":"23.108638843843046","longitude":"72.49444770743139"}
]
Google map with Ajax Code:
<script type="text/javascript">
// Check DOM Ready
$(document).ready(function() {
// Execute
(function() {
// Map options
var options = {
zoom: 6,
center: new google.maps.LatLng(23.039567700000000000, 72.566004499999960000), // Centered
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
// Init map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
$.ajax({
url: 'get-locations.php',
success:function(data){
var obj = JSON.parse(data);
var totalLocations = obj.length;
for (var i = 0; i < totalLocations; i++) {
// Init markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj[i].latitude + ',' + obj[i].longitude),
map: map,
title: 'Click Me ' + i
});
// Process multiple info windows
(function(marker, i) {
// add click event
google.maps.event.addListener(marker, 'click', function() {
infowindow = new google.maps.InfoWindow({
content: 'Hello, World!!'
});
infowindow.open(map, marker);
});
})(marker, i);
}
}
});
})();
});
</script>
When I tried to pass static latitude & longitude inside the loop marker is displayed:
position: new google.maps.LatLng(23.046100780353495,72.56860542227514),
but not working with dynamic with loop.
Any idea why markers are not displaying?
Thanks.
You're passing the coordinates incorrectly to the google.maps.LatLng constructor. There should be two parameters separated by a comma but you're concatenating them as a string.
The code should look like this:
position: new google.maps.LatLng(obj[i].latitude, obj[i].longitude)
I have implemented a google map with multiple markers but what i am failing to do is how to add a unique label for each marker i.e. Each marker needs have a letter:e.g.
Marker 1 needs to display 'A'
Marker 2 needs to display 'B'
Marker 3 needs to display 'C'
Marker 4 needs to display 'D'
...
an example of what i am trying to achieve is: http://www.athenos.com/locator/ --- enter 11205 in the zip search
here is a portion of my map code - my init and add_marker methods:
init : function() {
var self = this;
// set map property
var map = new google.maps.Map(self.dom_element, self.options);
self.map = map;
// set some other shit
new google.maps.Size(95, 77),
new google.maps.Point(0,0),
new google.maps.Point(47, 76);
// creating new bounds
var bounds = new google.maps.LatLngBounds();
// for loop to iterate through locations
for (var i = 0; i < self.locations.length; i++) {
// extend the bounds
bounds.extend(self.locations[i].latlng);
// add the marker
self.add_marker(self.locations[i].latlng, i);
}
// centers the map based on the existing map markers
self.map.fitBounds(bounds);
},
add_marker : function(latlng, marker_index) {
var self = this;
var marker = new google.maps.Marker({
position: latlng,
map: self.map,
icon: self.map_icon,
zIndex: 998,
id: marker_index // give the marker an ID e.g. 0, 1, 2, 3 - use this for indexing the listed venues
});
google.maps.event.addListener(marker, 'mouseover', function(event) {
var this_marker = this;
// executes handler and passes the marker as 'this' and event data as an argument
self.handle_marker_mouseover.call(self, this, event);
this_marker.setZIndex(999);
});
google.maps.event.addListener(marker, 'mouseout', function(event) {
// executes handler and passes the marker as 'this' and event data as an argument
self.handle_marker_mouseout.call(self, this, event);
});
google.maps.event.addListener(marker, 'click', function(event) {
// executes handler and passes the marker as 'this' and event data as an argument
self.handle_marker_click.call(self, this, event);
});
},
...
Please help.
Thanks in advance
just try to locate your icon, in marker's prop, at this url:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=7|00FF00|000000
So iterate with letters over the first part of the chld querystring parameter, and don't forget to choose your marker's color (latest two part, pipe separated)
Take a look at the article below. It's very simple. Use a marker with numeric labels or a marker with alphabet label (A,B..)
Multiple marker with labels in google map
for (i = 1; i <= markers.length; i++) {
var letter = String.fromCharCode("A".charCodeAt(0) + i - 1);
var data = markers[i - 1]
var myLatlng = new google.maps.LatLng(data.lat, data.lng);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: data.title,
icon: "http://maps.google.com/mapfiles/marker" + letter + ".png"
});
(function (marker, data) {
google.maps.event.addListener(marker, "click", function (e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
Go to this article for more details
Multiple marker with labels in google map
Wonder if anyone can help me, I have setup a google map all works nicely. The only thing I cant work out how to do is to open an info window based on ID from an external html link that's not in the JS.
function initialize() {
// Create the map
// No need to specify zoom and center as we fit the map further down.
var map = new google.maps.Map(document.getElementById("map"), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true
});
infowindow = new google.maps.InfoWindow();
// Custom markers
var icon = "img/marker.png";
// Define the list of markers.
// This could be generated server-side with a script creating the array.
var markers = [
{ val:0, lat: -40.149049, lng: 172.033095, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
{ val:1, lat: -41.185765, lng: 174.827516, title: "Title", html: "<div style='text-align:left'><h4 style='color:#0068a6;font-size:16px;margin:0px 0px 10px 0px;'>Title</h4><strong>Telephone</strong><br /><br />Address</div>" },
];
// Create the markers ad infowindows.
for (index in markers) addMarker(markers[index]);
function addMarker(data) {
// Create the marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(data.lat, data.lng),
map: map,
title: data.title,
icon: icon,
id: data.val
});
// Create the infowindow with two DIV placeholders
// One for a text string, the other for the StreetView panorama.
var content = document.createElement("DIV");
var title = document.createElement("DIV");
title.innerHTML = data.html;
content.appendChild(title);
// Open the infowindow on marker click
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(content);
infowindow.open(map, this);
map.setCenter(this.position);
console.log(this.id);
});
}
// Zoom and center the map to fit the markers
// This logic could be conbined with the marker creation.
// Just keeping it separate for code clarity.
var bounds = new google.maps.LatLngBounds();
for (index in markers) {
var data = markers[index];
bounds.extend(new google.maps.LatLng(data.lat, data.lng));
}
map.fitBounds(bounds);
}
<p id="1">link to open marker</p>
Any help would be gratefully appreciated
Richard :)
The Golden Goose
Then in your js have a function to open the infowindow (such as show()) which takes the properties from that link (opening id 7).
function show(id){
myid = id;
if(markers[myid]){
map.panTo(markers[myid].getPoint());
setTimeout('GEvent.trigger(markers[myid], "click")',500);
map.hideControls();
}
}
That's the function I used previously with one of the marker managers from v2. You have to make sure you set an id for each marker as you set it and then you can call it.
The one thing I made sure of (to simplify matters) was to make sure the map marker set/array was exactly the same as the sql result I used on the page. That way, using id's was a piece of cake.