display data in a loop using javascript - javascript

I'm trying to get the markers longitude and latitude and display them on the map but I'm not getting any result, my parser.php file is working and fetching the data from the database i just need to format it into javascript anyone ?
<script type="text/javascript">
function initialize() {
var mapOptions = {
center: { lat: -25.363882, lng: 131.044922},
zoom: 14
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
$.getJSON('parser.php', function(items) {
for (var i = 0; i < items.length; i++) {
(function(item) {
addMarker(item.lat, item.lon);
})(items[i]);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
parser.php output
[{"0":"33.880561","lat":"33.880561","1":"35.542831","lon":"35.542831"},{"0":"-25.363882","lat":"131.044922","1":"35.513477","lon":"35.513477"}]

addMarker needs to take map as an argument.
function addMarker(map, lat, long) {
var latlong = google.maps.LatLng(lat, long);
return new google.maps.Marker({
position: latlong,
map: map
});
}
Then your loop should be:
for (var i = 0; i < items.length; i++) {
item = items[i];
addMarker(map, item.lat, item.lon);
}
You don't need to put the addMarker calls into a closure, because these aren't separate callbacks.

Related

Javascript & PHP show multiple trackers in Google Maps API

Currently, I'm developing a system that will bring all latitude and longitude from MySQLi DB, and will output every data on the page. Here is my PHP code (working without any problem):
header('Content-Type: text/html; charset=utf-8');
require('database.php');
$query = mysqli_query($mysqli, "SELECT * FROM `tracking`");
if (!$query)
{
die('Error: ' . mysqli_error($mysqli));
}
if(mysqli_num_rows($query) > 0){
$getList = array();
while ($row = mysqli_fetch_assoc($query)) {
$getList[] = $row;
}
for($i = 0, $l = count($getList); $i < $l; ++$i) {
echo $getList[$i]['lat'].",".$getList[$i]['lon']."\n";
}
}
e.g output: -71.99991299555996,-83.18116602 -22.809918399999997,-43.4211132 -22.8540416,-43.2488448
Now, I need bring all data and put into an array, and put whole latitude/longitude to markers in Google Maps. Check what I have tried:
var check = false;
function refreshAll() { // This function will be called every 60 seconds
var locations = [];
locations.length = 0;
$.ajax({
type: "GET",
url: "show.php",
success: function(x)
{
var items = x.split("\n");
for(i=0; i<items.length; i++){
var data = items[i];
if ((items[i]).length > 1) {
locations.push(items[i].trim());
}
}
if (check == false) { // this will avoid map refreshing, I need only markers update.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
check = true;
}
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
alert(locations[i]);
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
}
}
});}
The problem is: the markers is not being set, and have no errors in console. I'm working on this in the last two days and can't find any solution. Can you help me? Thank you.
As you can see here in the docs, the LatLng object is different than the one you are using.
So, replace:
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].trim()),
map: map
});
With
locations[i] = locations[i].trim().split(',');
var latLng = {lat: Number(locations[i][0]), lng: Number(locations[i][1])};
marker = new google.maps.Marker({
position: latLng,
map: map
});
Check out, the map object is in your infoWindow variable, try to set there the positions.
This should be used inside the locations loop.
var pos = {
lat: latitude,
lng: longitude
};
infoWindow.setPosition(pos);

Toggle Show/Hide Google Marker with 1 button

I am trying to toggle a button which will hide/show the google marker placed in the map. I have been searching for an answer on SOF but all offered array method. I am wondering if it is possible to do it without array.
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 1.3420894594991328, lng: 103.83490918886719},
});
var ntuc = {
lat: 1.32805676,
lng: 103.9216584
};
var ntucmap = new google.maps.Marker({
position: ntuc,
map: map,
icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
});
}
function toggleNTUCmap() {
if (!ntucmap.getVisible()) {
ntucmap.setVisible(true);
} else {
ntucmap.setVisible(false);
}
}
Button
<button class="button-oj pure-button" onclick="toggleNTUCmap()">
<i class="fas fa-hospital"></i> NTUC</button>
For function toggleNTUCmap(), I have tried the following which still won't work.
ntucmap.setMap(ntucmap.getMap() ? null : map);
Can't you do something like this?
function clearMap(map) {
for(var i = 0; i<ntucmap.length; i++){
ntucmap[i].setMap(null);
}
}
and for the show part
function setMapOnAll(map) {
for (var i = 0; i < ntucmap.length; i++) {
ntucmap[i].setMap(map);
}
}
Then to have it in one button you can keep a counter with your button and when it's even do one function when it's odd do the other?
// Adds a marker at the center of the map.
var ntuc = {lat: 1.32805676, lng: 103.9216584};
addMarker(ntuc);
setMapOnAll(null);
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map,
icon: 'https://maps.google.com/mapfiles/kml/paddle/blu-stars.png'
});
markers.push(marker);
}
// Sets the map on all markers in the array.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}
// Show/Hide Markers
var counter = 0;
function toggleMarkers() {
if (counter == 0) {
setMapOnAll(map);
counter = 1;
} else {
setMapOnAll(null);
counter = 0;
}
}
In the end, I used array to save all the markers. Based on the button which user used to toggle, it will determine whether it marker(s) will be shown on the map or not.

Remove markers from map before adding new markers

I have a map where initially the markers load coming from the database, Then i have a time based Ajax request which gets the records again after every 1 minute.
Following is the code where i am using setMapOnAll(null) as from the Google maps Documentation, But its not working.
success: function(data){
var positions = [];
$.each(data.riders, function(index, value) {
positions.push({
lat: value.rider_location.lat,
lng: value.rider_location.lng,
content: value.name,
id : value.id
});
});
map.setCenter({
lat: parseInt(positions[0].lat),
lng: parseInt(positions[0].lng)
});
var infowindow = new google.maps.InfoWindow();
var marker,
i;
setMapOnAll(null); //Remove the existing markers
while(positions.length){
positions.pop().setMap(null);
}
for (i = 0; i < positions.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}
}
How can i remove the existing markers before adding new ones.
there is method marker.setMap(null) as google docs https://developers.google.com/maps/documentation/javascript/markers
you need create array of markers then remove all from map in loop by call method marker.setMap(null)
var markers = [];
for (i = 0; i < positions.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(positions[i].lat,positions[i].lng),
map: map,
id : positions[i].id,
});
markers.push(marker);
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
}
}) (marker, i));
}
You should add this function to your code and call it where you add new markers then add new markers. This will delete the previous markers.
function setMapOnAll(map) {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(map);
}
}

Google maps api and geocoding api - issues adding markers

I will start by saying that I am relatively new to JS, so please forgive my ignorance if this is obvious.
I am trying to add markers to a google map. I have created an array coordList, then used the geocoding api to get the lag and long from the addresses and pushed them into coordList.
I am now trying to use the coordList array to plot markers on the map, however I cannot seem to get the values from the coordList array. When I run console.log(typeof coordList) - it tells me it's an object, but when i look at the array with console.log(coordList) it just looks like a normal array?
var coordList = [];
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLong(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?address=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var lat = data.results[0].geometry.location.lat;
var lng = data.results[0].geometry.location.lng;
var coords = [];
coords.push(lat);
coords.push(lng);
//push coords into coordList
coordList.push(coords);
});
}
}
// Loop through the results array and place a marker for each
// set of coordinates.
function addMarkers(coordList) {
for (var i = 0; i < coordList.length; i++) {
var coords = coordList[i];
var latLng = new google.maps.LatLng(coords[0],coords[1]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
getLatLong(address);
addMarkers(coordList);
Your problem is that $.getJSON() is an asynchronous request and your code executes addMarkers() before than $.getJSON() finishes, so coordList is empty.
You can add the markers inside $.getJSON() callback. For example:
var address = [];
address.push('52+Kalynda+pde,+bohle+plains,+QLD')
address.push('51+Frank+St,+Kirwan+QLD+4817');
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: new google.maps.LatLng(-19.259854,146.8001348),
mapTypeId: 'roadmap'
});
}
function getLatLongAndAddMarkers(address){
var index;
for (index = 0; index < address.length; ++index) {
var request = 'https://maps.googleapis.com/maps/api/geocode/json?dress=' + address[index] + '&key=[MY_key]';
$.getJSON( request, function( data ) {
var latLong = new google.maps.LatLng(data.results[0].geometry.location);
//add markers here
var marker = new google.maps.Marker({
position: latLong,
map: map
});
});
}
}
getLatLongAndAddMarkers(address);

Show all geopoints of parse.com in google maps

I'm trying to take all the geopoints from a class in parse.com and show them as markers in a google map. (about only 1 geoipoin, lat lng, is working like a charm so here is the code)
function businessProfile(uid) {
Parse.initialize("APPID", "JSKEY");
var bprofile = Parse.Object.extend("magazia");
var query = new Parse.Query(bprofile);
query.notEqualTo("objectId", null);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) { var object = results[i];
var locationsBlock = {};
locationsBlock = JSON.parse(JSON.stringify(object));
var location = {};
location = JSON.parse(JSON.stringify(locationsBlock.latlon));
var lat = location.latitude;
var lon = location.longitude;
var magname = object.get('name');
setData(magname, lat, lon);
}
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
}
So with the code above i get all the geopoints of 16 different rows and i push them into an array (i hope i do it properly), which array is declared outside of the function because i call it again on the map initialiazation function below.
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {lat: 34.9, lng: 111.2}
});
setMarkers(map);
}
function setData(magname, lat, lon){
var arlat = [];
arlat.push(magname, lat, lon);
console.log(arlat);
}
function setMarkers(map) {
for (var i = 0; i < arlat.length; i++) {
var arlat = arlat[i];
var marker = new google.maps.Marker({
position: {lat: arlat[1], lng: arlat[2]},
map: map,
title: arlat[0]
});
}
}
So now i'm stuck on how to place each geopoint into the map with markers.
I know it has to do with the "for loop" but i'm stucked there. Now it shows only the first on the list marker, and i want to show them all.
UPDATE
So one update on my code i've managed to pass all the names and the lat lon that i get from my class in parse and now i put them in the function setData()
Now the question is, how can i pass the arlat array in the setMarkers() since the setMarkers function takes the map variable from the initMap() and i want it to take also the arlat array from the setData() function so i can print in the right section the lat lon and name? Here is a preview of the console.log(arlat)
Instead of pushing three variables:
arlat.push(magname, lat, lon);
You probably should push an object, like this:
arlat.push({lat: lat, lon: lon});
Then We just need to iterate over the pins (you could do it with a for loop, but a forEach might be simpler because you don't have to index into the array, just use a callback function that accepts the array element)...
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
icon: iconBase + 'marker.png',
title: 'Hello World!'
});
arlat.forEach(function(positionObject) {
var pin = new google.maps.Marker({
position: {
lat: positionObject.lat,
lon: positionObject.lon
},
map: map,
//title: positionObject.title, //if title property is set above
icon: 'http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00ff00' //green pin, more available
});
});
Does that work for you? For more info about icons, checkout the google maps API (which you likely already have looked at)
UPDATE - based on your update, I noticed you are reassigning the value of arlat, which conflicts with the foreach iterations. I have changed it to use objects, and not overwrite the array object - see this plunkr or the code snippet below.
function initialize() {
var arlat = [];
setData('a', 34.0, 111.2);
setData('v', 30.1, 116.3);
initMap();
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 3,
center: {
lat: 34.9,
lng: 111.2
}
});
setMarkers(map);
}
function setData(magname, lat, lon) {
//notice how we name the properties below: name, lat, lon - these are referenced down below in setMarkers()
arlat.push({
name: magname,
lat: lat,
lon: lon
});
}
function setMarkers(map) {
for (var i = 0; i < arlat.length; i++) {
var marker = new google.maps.Marker({
position: {
lat: arlat[i].lat,
lng: arlat[i].lon
},
map: map,
title: arlat[i].name
});
}
}
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map {
height: 90%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<div id="map"></div>

Categories