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)
Related
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();
I have some JSON data which i want to appear on google map. But the thing is its showing nothing. The JSON data will load from a server where the index file is also located. when i try to debug the problems i got some errors that i didn't understood. So, here is my data:
var map, infowindow; ////
var json = $.getJSON( "file.json", function( json ) {
function initialize() {
var mapOptions = {
////
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var bounds = new google.maps.LatLngBounds();
var responses = json.ResponseData;
for(var i = 0; i <= responses.length; i++) {
// Adding a new marker for the object
var position =
new google.maps.LatLng( responses.CoordinateY, responses.CoordinateX ); ////
bounds.extend( position ); ////
var marker = new google.maps.Marker({
position: position, ////
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
title: responses.BuildingName
});
// Adding a new info window for the object
var clicker = addClicker(marker, responses.BuildingName); ////
} map.fitBounds( bounds ); ////
// Adding a new click event listener for the object
function addClicker(marker, content) {
google.maps.event.addListener(marker, 'click', function() {
if (infowindow) {infowindow.close();}
infowindow = new google.maps.InfoWindow({content: content});
infowindow.open(map, marker);
});
}
}
google.maps.event.addDomListener(window, 'load', initialize);
});
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB6U22yg_ty9a4LFvJi6E0rYCyGwYt04Xk&callback=json">
</script>
<script src="https:////cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<div id="map-canvas"></div>
the json data file link is JSON DATA
and here is the link of the html file HTML
The thing is i want to show the markers on google map. The json file will be updating all time.
Thanks
The callback in your API load is incorrect. json is not a function.
I have put together this script (note: I'm using jQuery 1.11.2) that gets lat long coordinates from a PHP operation (used for something else) and displays a map with a customized marker and infowindow that includes HTML for formatting the information that is displayed.
<script src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript">
var maplat = 41.36058;
var maplong = 2.19234;
function initialize() {
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( maplat, maplong ); // Coordinates
var mapOptions = {
center: latlng,
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
streetViewControl: false,
zoomControl: false,
mapTypeControl: false,
disableDoubleClickZoom: true
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
// CREATE AN INFOWINDOW FOR THE MARKER
var content = 'This will show up inside the infowindow and it is here where I would like to show the converted lat/long coordinates into the actual, human-readable City/State/Country'
; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow({
content: content,maxWidth: 250
});
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: "A SHORT BUT BORING TITLE",
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
What I'm trying to achieve is to do a reverse geocode on the coordinates stored in the latlng variable and get back the results of that in a "City, State, Country" format and insert that into the HTML for the informarker stored in the "content" variable.
Have tried multiple approaches without success. Please note that I've deliberately left out the reverse geocoding script I tried to use for clarity purposes.
Edit: I've adjusted the script presented here to comply with the rules about it being clear, readable and that it actually should work. I also include a link to a CodePen so that you can see it in action: Script on CodePen
Regarding including the script for reverse geocoding, what I did was a disaster, only breaking the page and producing "undefined value" errors. I'd like to learn the correct way of doing this by example, and that's where the wonderful StackOverflow community comes in. Thanks again for your interest in helping me out.
Use a node instead of a string as content , then you may place the geocoding-result inside the content, no matter if the infoWindow is already visible or not or when the result is available(it doesn't even matter if the InfoWindow has already been initialized, a node is always "live").
Simple Demo:
function initialize() {
var geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(52.5498783, 13.42520);
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 18,
center: latlng
}),
marker = new google.maps.Marker({
map: map,
position: latlng
}),
content = document.createElement('div'),
infoWin = new google.maps.InfoWindow({
content: content
});
content.innerHTML = '<address>the address should appear here</address>';
google.maps.event.addListener(marker, 'click', function() {
infoWin.open(map, this);
});
geocoder.geocode({
location: latlng
}, function(r, s) {
if (s === google.maps.GeocoderStatus.OK) {
content.getElementsByTagName('address')[0].textContent = r[0].formatted_address;
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>
Here's how I would do it:
function reverseGeocoder(lat, lng, callback) {
var geocoder = new google.maps.Geocoder();
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
geocoder.geocode({"latLng" : point }, function(data, status) {
if (status == google.maps.GeocoderStatus.OK && data[0]) {
callback(null, data[0].formatted_address);
} else {
console.log("Error: " + status);
callback(status, null);
}
});
};
And basically you would call the function like:
reverseGeocoder(lat, lng, function(err, result){
// Do whatever has to be done with result!
// EDIT: For example you can pass the result to your initialize() function like so:
initialize(result); // And then inside your initialize function process the result!
});
I was looking over S.O. and found two questions that combined would solve a problem I am having.
I would like to post pct markers onto google map from Apex report.
passing variable from report works.. javascript:LOCATION(#LOCATION#);
but I can't seem to get the javascript to run.
thanks
<script type="text/javascript">
function LOCATION(pLoc){
var Loc = (pLoc);
var locations = ['+Loc+'];
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}}
})(marker, i));
}
}
</script>
thanks for your time.
Your Query:
SELECT stragg(a.location) as location, a.region
FROM
(SELECT DISTINCT rownum
, '['||''''||'test'||''''|| c.lon ||','|| c.lat ||', '||rownum|| ']' as location
, a.pct_name
, b.election_code_id
, c.region
FROM ecms.prv_pcts a
, ecms.sites_assign b
, ecms.sites_details c
WHERE b.site_id = c.site_id
AND b.pct_id = a.prv_pct_id
AND a.pct_name NOT LIKE 'ALL PR%'
AND b.election_code_id IS NOT NULL
AND b.election_code_id = '117'
ORDER by 1, 2
) a
GROUP BY a.region
Would give an output of:
['testLON',LAT,1],['testLON2',LAT2,2]
Calling function LOCATION with these values would provide the function with multiple parameters.
Thus, locations[][] wouldn't exactly work as pLoc is not an array holding arrays. You could fix this by using
SELECT '['||stragg(a.location)||']' as location, a.region
Also,
var locations = ['+Loc+']; kind of defeats the purpose, no?
DISTINCT ROWNUM?
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