I am trying to add sidebar. I am using name variable for links on the sidebar which are fetched from the database and it is available to me as an array. I am not able to loop twice as that puts QUERY_LIMIT to the google database.
Can anybody provide me logic on the way how to work on this functionality?
Here is my script:
<script type="text/javascript">
var markers = [];
var side_html = "";
var icon1 = "prop.png";
var icon2 = "office.png";
var locations = <?php echo $add_js ?>;
var name = <?php echo $name_js ?>
//function that will be used to handle clicks on the links in the sidebar
function myclick(num) {
google.maps.event.trigger(locations[num], "click");
}
function geocodeAddress(i)
{
geocoder.geocode({'address' : locations[i]},
function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, i);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
function createMarker(latlng,i) {
var marker = new google.maps.Marker({
map : map,
icon : icon1,
position : latlng
});
var infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150,50),
disableAutoPan: true
});
google.maps.event.addListener(marker, 'mouseover', function() {
marker.setIcon(icon2);
infowindow.setContent(locations[i]);
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'mouseout', function() {
marker.setIcon(icon1);
infowindow.setContent(locations[i]);
infowindow.close(map, marker);
});
return marker;
}
var map = new google.maps.Map(document.getElementById('map'), {
zoom : 10,
center : new google.maps.LatLng(28.6139, 77.2089),
mapTypeId : google.maps.MapTypeId.ROADMAP
});
//var infowindow = new google.maps.InfoWindow({size: new google.maps.Size(150,50)});
var geocoder = new google.maps.Geocoder();
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name + '<br />';
document.getElementById("side_bar").innerHTML = side_html;
}//end of for loop
</script>
I am getting proper markers in the output, but as the sidebar links i am getting whole of the name array each time and the link is not responding even to click events.
if "name" is an array, this should work:
for (var i = 0 ; i < locations.length; i++) {
geocodeAddress(i);
// link to the sidebar HTML that will open the info window for the record being processed
side_html += '' + name[i] + '<br />';
}//end of for loop
document.getElementById("side_bar").innerHTML = side_html;
Solved my problem at last!
I needed to split my array of strings first before using them to display in the sidebar link.
var name = names[i].split(",");
Final Soltion code:
for (var i = 0 ; i < locations.length; i++)
{
geocodeAddress(i);
var name = names[i].split(",");
side_html += '' + name + '<br />';
}
document.getElementById("side_bar").innerHTML = side_html;
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>
Sometimes, when I click on a marker once, all of the markers disappear for a second and reappear. Then I have to click again on a marker for the click event to register and the Info-Box to display. I am pretty sure this is also the reason why my markers don't disappear when I call the clearMarkers() function if I haven't already clicked on a marker. Here is my code:
var map;
var markersArray = [];
var cat = "restaurants, All";
var C = [...];
var D = [...];
function initMap() {
// Create a map object and specify the Div element to display it on
loc = {lat: 41.902783, lng: 12.496366};
map = new google.maps.Map(document.getElementById('map'), {
center: loc,
zoom: 14,
disableDefaultUI: true
});
// Displays all of the markers when page loads, all restaurants
getJsonData('yelpdata.php?cat=restaurants, All&lat='+loc.lat+'&lng='+loc.lng, map);
var filtersPanel = document.getElementById('filtersPanel');
var textField1 = document.getElementById('userInput');
// Displays the markers according the value the user is typing (cat)
function useValue() {
clearMarkers();
var textFieldVal = textField1.value;
var ind = findIndex(textFieldVal);
if (ind != -1) {
cat = D[ind];
}
getJsonData('yelpdata.php?cat='+cat+'&lat='+loc.lat+'&lng='+loc.lng, map);
}
// Text box event handlers
//textField1.oninput = useValue;
textField1.onchange = useValue;
textField1.addEventListener("awesomplete-selectcomplete", useValue);
google.maps.event.addListener(map, 'click', function(event) {
latitude = event.latLng.lat();
longitude = event.latLng.lng();
newCenter = {lat: latitude, lng: longitude};
map.setCenter(newCenter);
loc = newCenter;
useValue();
});
var autocomplete = new Awesomplete(textField1, {
list: C,
filter: Awesomplete.FILTER_STARTSWITH,
minChars: 1,
autoFirst: true
});
// Displays the filters panel in the top-left of the screen
map.controls[google.maps.ControlPosition.TOP_LEFT].push(filtersPanel);
}
function findIndex(cat) {
for(var i=0; i<C.length; i++) {
if(C[i] == cat)
return i;
}
return -1;
}
function clearMarkers() {
// Clears the markers from the map and array
for (var i=0; i < markersArray.length; i++) {
markersArray[i].setMap(null);
}
markersArray = [];
}
function getJsonData(url, map) {
// Using AJAX to get the JSON data from the 'yelpdata.php' file and display markers with info-boxes on the map
var request = new XMLHttpRequest; // the main object to request the XML
request.onreadystatechange = function() { // when the request changes state
if (request.readyState == 4) { // success, we have recieved the XML object from sending the request
var json = request.responseText;
var obj = JSON.parse(json);
var numMarkers = obj.businesses.length;
document.getElementById("numResults").innerHTML = numMarkers + " results";
for (var i = 0; i < obj.businesses.length; i++) {
(function(index) {
// Getting all of the attributes for each business from the JSON
var business = obj.businesses[index];
var name = business.name;
var catArr = business.categories;
var catStr = "";
for (j=0; j < catArr.length; j++) {
if (j == 0) {
catStr += catArr[j].title;
} else if (j > 0) {
catStr += ", " + catArr[j].title;
}
}
var reviews = business.review_count;
var rating = business.rating;
var address = business.location.address1 + ", " + business.location.city + ", " + business.location.state;
var coord = {lat: business.coordinates.latitude,
lng: business.coordinates.longitude};
var url = business.url;
var img_url = business.image_url;
// Creating the info-box
var markerInfo = document.createElement('div');
var title = document.createElement('strong'); // name
title.textContent = name;
var text0 = document.createElement('text'); // categories
text0.textContent = catStr;
var text1 = document.createElement('text'); // address
text1.textContent = address;
var text2 = document.createElement('text'); // reviews
text2.textContent = reviews + " reviews";
var text3 = document.createElement('text'); // rating
text3.textContent = rating + " stars";
// Appending the text to the info-box
markerInfo.appendChild(title);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text0);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text1);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text2);
markerInfo.appendChild(document.createElement('br'));
markerInfo.appendChild(text3);
// create the marker on its according position and append into array
var marker = new google.maps.Marker({
map: map,
position: coord
});
// change the opacity of the markers according to rating
if (rating >= 4) {
marker.setOpacity(1.0);
} else if (rating >= 2.5 && rating < 4) {
marker.setOpacity(0.8);
} else if (rating < 2.5) {
marker.setOpacity(0.6);
}
// set the info-box to the marker on click
infoWindow = new google.maps.InfoWindow;
marker.addListener('click', function() {
console.log("Registering");
infoWindow.setContent(markerInfo);
infoWindow.open(map, marker);
});
markersArray.push(marker);
})(i);
}
}
};
request.open('GET', url); // initialize the request
request.send(); // send the request
}
Lets see if this helps...
In this batch of code you are building the infobox content but not setting it until the click event.
// set the info-box to the marker on click
infoWindow = new google.maps.InfoWindow;
marker.addListener('click', function() {
console.log("Registering");
infoWindow.setContent(markerInfo);
infoWindow.open(map, marker);
});
try moving the line that sets the content outside the click event. you should only need to set it once anyway
infoWindow = new google.maps.InfoWindow;
infoWindow.setContent(markerInfo);
marker.addListener('click', function() {
console.log("Registering");
infoWindow.open(map, marker);
});
I am trying to delete a marker from google maps through a custom delete button. I have added the button and other information in the infowindow.
I have a function which deletes the marker from the map, the problem is when I press the delete button the function isnt called.
Here is my code:
function initMap() {
var jsonData = {$pointsArray};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
maxzoom: 15,
center: {
lat: 38,
lng: -77
}
});
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
var bounds = new google.maps.LatLngBounds();
for (var i = 0, len = jsonData.length; i < len; ++i) {
var point = jsonData[i];
var uniqueId = 1;
var markers = [];
var marker = new google.maps.Marker({
position: new google.maps.LatLng(point.Lat, point.Lon),
map: map,
title: point.Title
});
bounds.extend(marker.position);
marker.id = uniqueId;
uniqueId++;
var contentString = '<div id="content">'+
'<h4 id="pointId" > ' + point.Title + '</h4>'+
'<h6 >City: ' + point.City + '</h6>'+
'<h6 >Latitude: ' + point.Lat+ '</h6>'+
'<h6 >Longitude: ' + point.Lon + '</h6>'+
'<h6 >Address: ' + point.Address + '</h6>'+
'<p data-placement="top" data-toggle="tooltip" title="Delete"><span class="glyphicon glyphicon-trash"></span></p>'
'</div>';
addInfoWindow(marker, contentString);
markers.push(marker);
}
function DeleteMarker(id) {
for (var i = 0; i < markers.length; i++) {
if (markers[i].id == id) {
markers[i].setMap(null);
markers.splice(i, 1);
return;
}
}
};
map.fitBounds(bounds);
}
Probably there is something wrong with the onclick attribute in the delete button, but I am not sure.
Help!
I think you have to use ' instead of " when you want to give marker.id as parameter because you used ' for the string and " for the attribute value. If you use " you just interrupt the attribute string for the onclick value.
In the rendered html, your function should look like this:
<p><a onclick="DeleteMarker('some id');"</a></p>
In order to achive that, put additional single quotes around the your id parameter:
onclick="deleteMarker('+"'"+ yourId +"'"+')
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.
I've got the following problem with Googlemaps.
I've created a createMarker function which returns a marker which I publish with addOverlay(). This works perfect, the marker get shown but the only problem is the click event voor the marker, I want a infowindow which is populated with the 'I want this text to be published' text, instead it gets populated with a var called html which I set in the beginning of my code (var html = 'test';), I received earlier a message with 'html is not defined', this is why is set the html var. Every infowindow has the text 'test' in it. I've tried using updateInfoWindow() but that doesn't work, anyone familiar with this problem? I can supply you with the full source but I think the createMarker function should be enough.
function GM_load() {
map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
map.enableScrollWheelZoom();
map.setMapType(G_HYBRID_MAP);
geocoder = new GClientGeocoder();
GM_showItems();
}
function GM_showItems() {
GDownloadUrl("modules/Googlemaps/ajax/getItems.php", function(data, responseCode) {
var xml = GXml.parse(data);
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
//start
var itemid = markers[i].getAttribute('id');
var title = markers[i].getAttribute('name');
var address = markers[i].getAttribute('address');
var city = markers[i].getAttribute('city');
var x = 0;
if (geocoder) {
geocoder.getLatLng(address + ' ' + city,
function(point) {
if (!point) {
alert(address + ' ' + city + " not found");
} else {
x = x+1;
Marker = createMarker(point, x);
map.addOverlay(Marker);
}
}
);
}
}
});
}
function createMarker(latlng, number) {
var marker = new GMarker(latlng);
marker.value = number;
GEvent.addListener(marker,"click", function() {
map.openInfoWindowHtml(latlng,'i want this text to be published');
});
return marker;
}
Solved.
I overwrite var html. not perfect but it works.