I have an array like this deviceId = [005305230001JIZZZZ, 085835360001NBGJZZ, 085835360002NBGJZZ].
The info window should show the deviceId and be displayed based on which marker is clicked. I started looking at JavaScript only a few days back and can't understand how the functions work and dont have the time right now to learn becauseI have to get this done. I saw a few implementations on this, but I think they have done the adding multiple markers differently using functions, I think. I couldn't understand it so I used for loop.
The latArray and lngArray have something like this [12.1456,12.5256,11.566] and [72.145,72.4557,75.23535]
I cant figure out how to add info windows for corresponding markers.
This is the code for map:
function initMap() {
var bounds = new google.maps.LatLngBounds();
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv);
map.setCenter(new google.maps.LatLng(latArray[0],lngArray[0]));
map.setZoom(18);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(latArray[i],lngArray[i]),
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
//bounds.extend(marker.getPosition());
console.log(latArray);
console.log(lngArray);
}
//map.fitBounds(bounds);
var infoWindow = new google.maps.InfoWindow({
content: contentString
});
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
}
How to show info window of corresponding markers.
This is content for marker:
contentString = '<div id = "content>'
+'<p style = "color:#000000">DeviceID<p>' +
'<p>'+ deviceId[i] + '<br></p>' //deviceId is the array with content
+ '</div>'
I read something about closures but didn't understand. Please help
Edit: I just tried this. I'm getting js?callback=initMap:34 InvalidValueError: setPosition: not a LatLng or LatLngLiteral: not an Object
What i tried:
var markerArray=[];
for(i=0;i<latArray.length;i++)
{
markerArray.push("new google.maps.LatLng("+ latArray[i]+","+lngArray[i]+")");
console.log(markerArray[i]);
}
console.log(markerArray[0]);
for(i=0;i<latArray.length;i++)
{
marker = new google.maps.Marker({
position: markerArray[i],
map: map,
title:"This is the place.",
// icon:"phone4.png"
});
var infoWindow = new google.maps.InfoWindow({
content: contentString[i]
});
marker.addListener('click', function(marker,contentString) {
infoWindow.open(map, marker);
});
}
So I will not bother you with the explanation how closures work (as you are saying your not interested in it now), I just supply you the solution:
// Your arrays with geo informations
var latArray = [-25.363, -26.263, -25.163];
var lngArray = [131.044, 131.144, 132.044];
// Your array with device information
var deviceIdArray = ["AAA", "BBB", "CCC"];
// Just create map according to the first geo info
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: latArray[0], lng: lngArray[0]},
zoom: 6
});
// Loop throuhg all geo info
latArray.forEach(function(lat, i) {
// For each one create info window
var infoWindow = new google.maps.InfoWindow({
content: '<div id="content>'
+ '<p style="color:#000000">DeviceID<p>'
+ '<p>'+ deviceIdArray[i] + '</p>'
+'</div>'
});
// For each one create marker
var marker = new google.maps.Marker({
map: map,
position: {lat: latArray[i], lng: lngArray[i]}
});
// Click on the currently created marker will show the right info window
marker.addListener("click", function() {
infoWindow.open(map, marker);
});
});
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map"></div>
Take a look at my function with map. It takes json object with some data from PHP and 'translate' it into array and then adds content to multiple markers (it is not dynamic in real time - you have to reload page). In addition it has a search box (which opens certain info window). If you don't understand do not hestitate to ask :).
//check if document is fully loaded, seetting a container for ajax call results
$(document).ready(function() {
var tablica = [];
// ajax call for action preparing set of names, descriptions, coords and slugs needed to render deatiled markers on map
$.ajax({
url: 'map/json_prepare',
dataType: 'json',
success: function(response) {
var obj = JSON && JSON.parse(response) || $.parseJSON(response);
obj.forEach(function(item, index, array)
{
tablica.push(item);
});
//call a function rendering a map itself
var map;
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 50.06561980, lng: 19.946850},
zoom: 12
});
////////////////////////////////////////////////////////////////////////////////////////////////////
// LOOP ADDING MARKERS FROM DB WITH PROPER INFO WINDOWS (DESCRIPTION AND LINKS)
// Add a markers reference
var markers = [];
$.each(tablica, function( key, value ) {
//markers
var myLatLng = {lat: value[1], lng: value[2]};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: value[0],
clickable: true,
animation: google.maps.Animation.DROP,
adress: value[5]
});
//infowindows
marker.info = new google.maps.InfoWindow ({
content: '<h1>'+ value[0] + '</h1>' + '<br>' + '<br>' + value[3] + '<br>' + value[5] +'<br>' + '<br>' + '' + 'Details' + '<br/>' +
'' + 'Take part in' + '<br>'
});
//eventlistener - after click infowindow opens
google.maps.event.addListener(marker, 'click', function() {
marker.info.open(map, marker);
});
//event listener - after dblclick zoom on certain event is set
google.maps.event.addListener(marker, 'dblclick', function() {
map.setZoom(18);
map.setCenter(marker.getPosition());
});
markers.push(marker);
});
// End of loop adding markers from db.
///////////////////////////////////////////////////////////////////////////////////////////////////////////
///additional event listener - rightclick to get back default zoom
google.maps.event.addListener(map, 'rightclick', function() {
map.setZoom(12);
map.setCenter(map.getPosition());
});
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
//CENTRING MAP AS ALL OF MARKERS IS VISIBLE//
//create empty LatLngBounds object
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < tablica.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(tablica[i][1], tablica[i][2]),
map: map
});
//extend the bounds to include each marker's position
bounds.extend(marker.position);
}
//now fit the map to the newly inclusive bounds
map.fitBounds(bounds);
/////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////
///SEARCH_BOX////////
///Here comes part of script adding search box
// Create the search box and link it to the UI element.
// Anchor search box and search button to the map.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
var button = document.getElementById('submitSearch');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(button);
//replacing polish characters on order to search without necessity typing them
function cleanUpSpecialChars(str)
{
str = str.replace(/[Ą]/g,"A");
str = str.replace(/[ą]/g,"a");
str = str.replace(/[Ę]/g,"E");
str = str.replace(/[ę]/g,"e");
str = str.replace(/[Ć]/g,"C");
str = str.replace(/[ć]/g,"c");
str = str.replace(/[Ł]/g,"L");
str = str.replace(/[ł]/g,"l");
str = str.replace(/[Ń]/g,"N");
str = str.replace(/[ń]/g,"n");
str = str.replace(/[Ó]/g,"O");
str = str.replace(/[ó]/g,"o");
str = str.replace(/[Ś]/g,"S");
str = str.replace(/[ś]/g,"s");
str = str.replace(/[Ź]/g,"Z");
str = str.replace(/[ź]/g,"z");
str = str.replace(/[Ż]/g,"Z");
str = str.replace(/[ż]/g,"z");
return str;
}
//Function, that search in array of markers, one which fits the key word written in searchbox.
$('#submitSearch').click(function() {
//Catching searched word and preparing its value for search process
var toSearch = $(input).val().trim();
toSearch = cleanUpSpecialChars(toSearch);
toSearch = toSearch.toLowerCase();
console.log('Szukana fraza -> ' + toSearch);
var results = [];
if (toSearch.length >=3) {
// Iterate through the array
$.each(markers, function (i, marker) {
//preparing certain elemnts of marker objects for search process
markers[i].title = cleanUpSpecialChars(markers[i].title);
markers[i].adress = cleanUpSpecialChars(markers[i].adress);
markers[i].title = markers[i].title.toLowerCase();
markers[i].adress = markers[i].adress.toLowerCase();
if (markers[i].title.indexOf(toSearch) > -1 || markers[i].adress.indexOf(toSearch) > -1) {
results.push(markers[i]);
}
});
if (results.length < 1) {
console.log ('nic');
$('#message2').slideDown(500, function () {
setTimeout(function () {
$('#message2').slideUp(500);
}, 5000);
});
}
// Close all the infoWindows, before rendering Search results.
markers.forEach(function (marker) {
marker.info.close(map, marker);
});
//Opens infWindows for multiple markers found and set bounds so that all markers found are visible
results.forEach(function (result) {
result.info.open(map, result);
bounds.extend(result.position);
});
map.fitBounds(bounds);
}
else{
//what if user has typed less than three characters in searchbox -> render flash mess.
$("#message").slideDown(500, function(){
setTimeout(function(){
$("#message").slideUp(500);
},5000);
});
}
});
//Enabling key Enter for triggering a search action.
$(input).keypress(function(e){
if(e.which == 13){//Enter key pressed
$('#submitSearch').click();//Trigger search button click event
}
});
},
//////////////////////////////////////////////////////////////////////////////////////////
//obsługa błędu, jeśli nie zostanie wyświetlona mapa
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
console.log(ajaxOptions);
alert('Map is broken. Please try again later.')
}
});
});
It will not qork here because it doesn't contain data from php.
Related
I work in Laravel project and I have module for displaying and removing all stores on a Google map if I choose only 1 store.
This is a duplicate question, however, why my function is not working setting the function showallmarks as null.
Question: How to remove all the marks displayed in the google maps once a button is clicked?
I have here the codes.
Show all marks:
showallmarks();
function showallmarks() {
$.each(locations, function(index, value) {
var position = new google.maps.LatLng(value.store_lat, value.store_long);
var title = value.branch_name;
var address = value.store_address;
var contentString = "<h5>" + title + "</h5>" + address;
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: position,
icon: google.maps.marker,
map: map,
zoom: 12
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
});
}
Once I click this button the showallmarks must not be shown on the Google map.
var markeronce;
$('button#addresses').click(function() {
//removing all marks
showallmarks(null);
var infowindow = new google.maps.InfoWindow({
content: "<span>Visit us on our store.</span>"
});
var address_href = $(this).val();
var commaPos = address_href.indexOf(',');
var coordinatesLat = parseFloat(address_href.substring(0, commaPos));
var coordinatesLong = parseFloat(address_href.substring(commaPos + 1, address_href.length));
var centerPoint = new google.maps.LatLng(coordinatesLat, coordinatesLong);
if (!markeronce) {
markeronce = new google.maps.Marker({
position: centerPoint,
map: map,
zoom: 8
});
} else {
markeronce.setPosition(centerPoint);
}
map.setCenter(centerPoint);
})
Add Button like
<input type="button" value="Delete" onclick="DeleteMarkers()" />
And try this function
<script type="text/javascript">
var markers = [];
function DeleteMarkers() {
//Loop through all the markers and remove
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
};
</script>
I have been working on this for a while now. I have looked at multiple stack overflow posts on the topic and several tutorials, but I have not been able to get infoWindow.close() to work.
I have even tried using jQuery to click $('#googleMap > div > div > div:nth-child(1) > div:nth-child(4) > div:nth-child(4) > div:nth-child(1) > div:nth-child(3)').click(); which actually seems to work in the browser console, but not when running the click listener.
Any suggestions or directions are much appreciated.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return function() {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
};
})(marker,contentStr,infoWindow));
}
}
Stephen's answer identifies the problem with the infowindow. I want to help you learn to write simpler code.
There is a lot of complication in this code that you don't need; in fact you can get rid of most of the code!
The code first converts the locs array to a very similar obj array that has a couple of fields renamed.
Then it converts this obj array to four individual arrays pointLoc, labels, descrip, and locale.
None of this conversion is needed.
Also, when naming an array, I recommend using a plural name for the array and the singular form of that name for an element of the array. You did this in some places, just not consistently.
There is a map.data.loadGeoJson(); call that doesn't do anything because no URL is provided.
You also don't need the function-that-returns-a-function in the click listener, if you provide a closure in a simpler way as in the code below.
Here's an example of how you could do the whole thing in a much simpler manner:
d3.csv( '/data/locs.csv', function( places ) {
var infoWindow;
var map = new google.maps.Map( document.getElementById('googleMap'), {
center: { lat: 39.8283, lng: -98.5795 },
zoom: 2
});
places.forEach( function( place ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( place.lat, place.long ),
map: map
});
google.maps.event.addListener( marker, 'click', function() {
if( infoWindow ) infoWindow.close();
var content =
'<div id="popcontent">' +
'<div id="siteNotice">' +
'</div>' +
'<h1 id="firstHeading" class="firstHeading">' + place.description + '</h1>' +
'<p>' + place.location + ', ' + place.country + '</p>' +
'</div>';
infoWindow = new google.maps.InfoWindow({
maxWidth: 300,
content: content
});
infoWindow.open( map, marker );
});
});
});
Your variable infoWindow goes out of scope when returning a function, and you not modifying the outer infoWindow, but the one passed into the function. Try this.
d3.csv('/data/locs.csv', function(locs){
var obj = [];
for(i=0;i<locs.length;i++) {
var country = locs[i].country;
var location = locs[i].location;
var lat = locs[i].lat;
var long = locs[i].long;
var description = locs[i].description;
obj.push({
con: country,
location: location,
lat: lat,
lng: long,
description: description
});
}
console.log(obj);
initMap(obj)
});
function initMap(obj, error) {
if (error){console.log("Error: "+error)}
var openInfoWindow = null;
var mapProp = {
center: {lat: 39.8283, lng: -98.5795},
zoom: 2
};
var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
var pointLoc = [];
var labels = [];
var descrip = [];
var locale = [];
for(i=0;i<obj.length;i++) {
pointLoc.push({lat: obj[i].lat, lng: obj[i].lng});
labels.push(obj[i].con);
descrip.push(obj[i].description);
locale.push(obj[i].location);
}
map.data.loadGeoJson();
for (var i = 0; i < pointLoc.length; i++) {
var coords = pointLoc[i];
var latLng = new google.maps.LatLng(coords.lat,coords.lng);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
var contentStr = '<div id="popcontent">'+
'<div id="siteNotice">'+
'</div>'+
'<h1 id="firstHeading" class="firstHeading">'+descrip[i]+'</h1>'+
'<p>'+locale[i]+', '+labels[i]+'</p>' +
'</div>';
var infoWindow = new google.maps.InfoWindow({
maxWidth: 300
});
google.maps.event.addListener(marker,'click', (function(marker,contentStr,infowindow){
infowindow.close();
return((function(infowindow) {
infowindow.setContent(contentStr);
infowindow.open(map, marker);
})(infowindow));
})(marker,contentStr,infoWindow));
}
}
I was able to handle it easily with jQuery trigger event.
jQuery('.gm-ui-hover-effect').trigger('click');
Just put above code inside addListener function of marker and don't forget to include jQuery in your script.
I have recently started working on google maps API V3 and right now I am stucked in a problem.
I have two markers plotted on my map. What I want is that on moving the mouse cursor on map, it continuously checks for latitude and when the latitude is equal to that of the marker present on map it should show an alert message.
The problem which I am facing is that it is working only for one marker, not for all markers present on map
Here is my code:
$.ajax({
type: "GET",
url: $('meta[name="_home_url"]').attr('content') + '/walkalong/' + position.coords.latitude + "/" + position.coords.longitude,
success: function (response) {
// Looping through all the entries from the JSON data
for (var i = 0; i < response.data.shops.length; i++) {
// Current object
var obj = response.data.shops[i];
// Sets the map marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(obj.latitude, obj.longitude),
map: map,
info: contentString,
optimized: false,
icon: pinIcon,
id: obj.shop_id,
animation: google.maps.Animation.DROP,
title: obj.title // this works, giving the marker a title with the correct title
});
google.maps.event.addListener(map, 'mousemove', function (event) {
Latfetch = event.latLng.lat().toFixed(4);
Longfetch = event.latLng.lng().toFixed(4);
if (Latfetch === obj.latitude) {
alert(obj.latitude);
}
});
and the JSON response is:
{"status":200,"data":{"shops":[{"shop_id":7,"name":"reebok","logo":"543813f8-cc75-4217-a3d4-bb08992f66af.png","latitude":"17.4539","longitude":"78.3902","shop_description":"","opening_time":"09:00:00","closing_time":"18:00:00","mobile":"4567896545","address_line1":"ameerpet","city":"Dispur","state":"Arunachal Pradesh","country":"India","pincode":"435645","baazar_area":"","front_image":"6c08a359-fb7f-4e09-af25-3c2d43a32327.jpg","distance":0.703},{"shop_id":9,"name":"ahex","logo":"86c6f7f8-625c-4a7a-aee4-10f7d16f1f12.jpg","latitude":"17.4519","longitude":"78.3879","shop_description":"","opening_time":"09:00:00","closing_time":"18:00:00","mobile":"4233488384","address_line1":"madhapur","city":"Panaji","state":"Goa","country":"India","pincode":"345678","baazar_area":"","front_image":"31e96273-c360-4b49-87d1-418bdac26dc3.jpg","distance":0.711}],"shopImages":[{"logo":"543813f8-cc75-4217-a3d4-bb08992f66af.png","front_image":"6c08a359-fb7f-4e09-af25-3c2d43a32327.jpg","internal_image":"e988011f-f2c1-4b08-8582-0f36e85dc4f9.jpg","rack_image":"rack.jpeg","product_image":"item.jpeg"}]}}
Anyone there who could help?
I can only guess it just works only for one because you can only add one listener for mousemove. You could add the event on the marker instead:
for (var i = 0; i < response.data.shops.length; i++) {
...
var marker = new google.maps.Marker({
...
});
marker.addListener('mousemove', function(event) {
var latfetch = event.latLng.lat().toFixed(4);
var longfetch = event.latLng.lng().toFixed(4);
var lat = this.position.lat();
if(latfetch === lat){
alert(lat);
}
});
}
Good afternoon, I created a map that fills markers with coordinates directly from my mysql database, the map is being generated correctly and markers work when I load the page. Every minute I get new coordinates in the bank and want to update the map with a time interval. For this I used the setInterval that calls the initialization function of the markers, however, are not creating new markers on the map, is always displaying the same, they only update when I give f5 on the page, ie if reloading the page works, but with no interval. He even winked on the map when the time set by the interval, but not updated.
My code:
<script src="js/markerclusterer.js"></script>
<script src="js/jquery-1.5.2.min.js"></script>
<script src="js/jquery.maskedinput-1.3.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
<?php
if($attmap_form > 0) {
echo 'myTimer = window.setInterval(refreshMapa,"'.$attmap_form.'");';
}
?>
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-25.4848801,-49.2918938),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
locations = [];
<?php
require('conecta.php');
$sql_lista = ("SELECT MONITLATITUDE,MONITLONGITUDE,MONITDATA,MONITHORA,MONITRAIO,MONITPROVEDOR,MONITVELOCIDADE FROM MONITORAMENTO where MONITHORA BETWEEN '$hora1_form' AND '$hora2_form' AND MONITDATA BETWEEN '$data1_form' AND '$data2_form' AND EQUIPIMEI = $imei");
$query_lista = mysql_query($sql_lista);
$achados_lista = mysql_num_rows($query_lista);
while ($achados_lista = mysql_fetch_array($query_lista)) {
$lat = $achados_lista['MONITLATITUDE'];
$lon = $achados_lista['MONITLONGITUDE'];
$Data = $achados_lista['MONITDATA'];
$hora = $achados_lista['MONITHORA'];
$raio = $achados_lista['MONITRAIO'];
$provedor = $achados_lista['MONITPROVEDOR'];
$velocidade = $achados_lista['MONITVELOCIDADE'];
echo 'locations.push ( {Data:"'.$Data.'", latlng: new google.maps.LatLng('.$lat.', '.$lon.'), hora:"'.$hora.'", raio:"'.$raio.'",provedor:"'.$provedor.'",velocidade:"'.$velocidade.'"} );';
}
?>
var bounds = new google.maps.LatLngBounds();
var infowindow = new google.maps.InfoWindow();
var markers = [];
for(var i=0;i < locations.length;i++ ) {
var marker = new google.maps.Marker({
position: locations[i].latlng,
map:map,
title:locations[i].hora
});
markers.push(marker);
bounds.extend(locations[i].latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
);
infowindow.open(map, marker);
}
})(marker, i));
}
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: 16,
gridSize: 60
});
map.fitBounds(bounds);
}
arrancaMapa();
function arrancaMapa() {
google.maps.event.addDomListener(window, 'load', initialize);
}
function refreshMapa() {
initialize();
arrancaMapa();
}
function clearMarkers() {
setAllMap(null);
}
function stopTimer() {
$("#campoAttMap").val("0");
clearInterval(myTimer);
}
</script>
You shouldn't have to call initialize more than once. You should implement a different logic, for example get the newest marker that is not in the map and add it via
var marker = new google.maps.Marker({
position: locations[i].latlng,
map:map,
title:locations[i].hora
});
markers.push(marker);
bounds.extend(locations[i].latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(
'<strong>Data: ' + locations[i].Data + '<br>Hora: ' + locations[i].hora + '<br></strong>Velocidade aproximada: ' + locations[i].velocidade + ' K/H<br>Raio aproximado de: ' + locations[i].raio + ' metros <br>Provedor: ' + locations[i].provedor + '<br>Latitude: ' + locations[i].latlng
);
infowindow.open(map, marker);
}
})(marker, i));
UPDATE:
I will add take the following approach. I don't like mixing PHP and Javascript together, I prefer using JSON and AJAX request.
Update your functions to look like this:
var map;
var markers = [];
setInterval(refreshMapa, 3000);
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(-25.4848801,-49.2918938),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var locations = [];
$.get("getmarkers.php", function(response){
for(var i = 0; i < response.markers.length; i++) {
var marker = response.markers[i];
var myMarker = {
Data: marker.Data,
latlng: new google.maps.LatLng(marker.lat, marker.lon),
hora: marker.hora,
raio: marker.raio,
provedor: marker.provedor,
velocidade: marker.velocidade
};
locations.push(myMarker);
addMapMarker(myMarker);
}
},'json');
markerClusterer = new MarkerClusterer(map, markers, {
maxZoom: 16,
gridSize: 60
});
map.fitBounds(bounds);
}
function refreshMapa() {
// make sure this one only returns markers that are new and not in the map
$.get("getnewmarkers.php", function(){
for(var i = 0; i < response.markers.length; i++) {
var marker = response.markers[i];
var myMarker = {
Data: marker.Data,
latlng: new google.maps.LatLng(marker.lat, marker.lon),
hora: marker.hora,
raio: marker.raio,
provedor: marker.provedor,
velocidade: marker.velocidade
};
locations.push(myMarker);
addMapMarker(myMarker);
}, 'json');
}
function addMapMarker(myMarker) {
var marker = new google.maps.Marker({
position: myMarker.latlng,
map:map,
title:myMarker.hora
});
markers.push(marker);
bounds.extend(myMarker.latlng);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('<strong>Data: ' + myMarker.Data + '<br>Hora: ' + myMarker.hora + '<br></strong>Velocidade aproximada: ' + myMarker.velocidade + ' K/H<br>Raio aproximado de: ' + myMarker.raio + ' metros <br>Provedor: ' + myMarker.provedor + '<br>Latitude: ' + myMarker.latlng);
infowindow.open(map, marker);
}
})(marker, i));
}
PS: I'm not sure if the implementation of the addMapMarker is correct I just assumed you had it right in the first place, you should check the documentation and make sure it is correct.
Yeah so the thing is, PHP is a server-side language that only gets executed when the page loads. I'm not sure exactly how you would expect your JS to update the markers, as there are no get/post anywhere. If you want to get data from the server, you have to contact the server.
This loop
while ($achados_lista = mysql_fetch_array($query_lista)) {
$lat = $achados_lista['MONITLATITUDE'];
$lon = $achados_lista['MONITLONGITUDE'];
$Data = $achados_lista['MONITDATA'];
$hora = $achados_lista['MONITHORA'];
$raio = $achados_lista['MONITRAIO'];
$provedor = $achados_lista['MONITPROVEDOR'];
$velocidade = $achados_lista['MONITVELOCIDADE'];
echo 'locations.push ( {Data:"'.$Data.'", latlng: new google.maps.LatLng('.$lat.', '.$lon.'), hora:"'.$hora.'", raio:"'.$raio.'",provedor:"'.$provedor.'",velocidade:"'.$velocidade.'"} );';
}
Only gets executed ONCE. The value of locations doesn't change.
You should read up on jQuery ajax requests. Make an HTTP request to a PHP file that returns the locations as JSON (just echo the JS array) and use the result to update the markers.
Reason:
There is no update function (or code blocks) to get updated or newly added DB info in your code. Also, you will not read and add new db info to your map data because your PHP code is only called once at initialization-time.
Using PHP codes, you will not do it because of the PHP features. PHP will only work on back-end service sides.
Suggestion:
1. You need client-side updates to access service side updates and receive them.
2. You need to add the updated or newly added db data to your Marker (map) array on client sides.
For this,
1. Add client side update features in AJAX or others to update the info to JSON objects.
2. Call the AJAX block (retrieving block or function to read in JSON object array and add them to map marker arrays).
3. Update null pointer of Map Markers to the new Map array.
Sorry for not creating a working code set based on your codes. It will take a fairly long while.
I have a forloop that has a call to a function inside of it. Within that function, I'm pushing values to an array called markers.
Is there a way to access the values of the markers array outside of the forloop?
Here's the code:
<script type="text/javascript">
// arrays to hold copies of the markers and html used by the side_bar
// because the function closure trick doesnt work there
var map = null;
geocoder = new google.maps.Geocoder();
var side_bar_html = "";
var icon = '';
var markers = [];
function codeAddress(this_address,index,callback) {
geocoder.geocode( { 'address': this_address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
callback.call(window,index,results[0].geometry.location)
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
function initialize() {
// create the map
var myOptions = {
zoom: 3,
center: new google.maps.LatLng(46.90, -121.00),
mapTypeControl: true,
mapTypeControlOptions: {style: google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (var i = 0; i < businesses.length; i++) {
codeAddress(businesses[i].address,i,function(i,point){
var description = businesses[i].description;
if(businesses[i].business_type == "Wine"){
//http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=A|00CC99|000000
icon = 'http://google-maps-icons.googlecode.com/files/wineyard.png';
}else if(businesses[i].business_type == "Golf"){
icon = 'http://google-maps-icons.googlecode.com/files/golf.png';
}else{
icon = 'http://google-maps-icons.googlecode.com/files/festival.png';
}
var marker = createMarker(point,businesses[i].name,description,icon);
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
});//End codeAddress-function
}//End for-loop
console.log(markers);
var markerCluster = new MarkerClusterer(map, markers);
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html,icon) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
icon: icon,
zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
markers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (markers.length-1) + ')">' + name + '<\/a><br />'+html+'<br />';
}
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(markers[i], "click");
}
</script>
As you can see, the last line says "var markerCluster = new MarkerClusterer(map, markers);" This is where I want to be able to access the information from.
Thanks!
The problem is you're not accounting for the asynchronous nature of the call to codeAddress. You're calling that function in a loop, which is triggering a series of calls to the Google Maps API.
You are running this line:
var markerCluster = new MarkerClusterer(map, markers);
...even before the callbacks have been triggered.
To fix, maintain a counter. Each time the callback is triggered increase that counter by 1. Once it is equal to businesses.length you know all the addresses have been geo-coded, and all markers have been added to the array. Now you can create the MarkerCluster.
Yes, Declare it before the for loop.
var markers
for(....
Bring the definition of the marker outside of the for loop ...
var markers = new Array ();
for (var i = 0; i < businesses.length; i++) {
markers[i] = ...