Google Map Information window - javascript

I am using google map which shows marker with information window...in which i display address but i want to show the name as well in information window when a marker is clicked. Any help will be highly appreciated.
function load()
{
var map = new GMap2(document.getElementById("map"));
map.setCenter(new GLatLng(-37.816667,144.966667), 10);
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var geocoder = new GClientGeocoder();
GDownloadUrl("shops.xml", function(data) {
var xml = GXml.parse(data);
shop = xml.documentElement.getElementsByTagName("shop");
for (var i = 0; i < shop.length; i++) {
var name= shop[i].getElementsByTagName("name");
name = name[0].childNodes[0].nodeValue;
var address= shop[i].getElementsByTagName("address");
address = address[0].childNodes[0].nodeValue;
geocoder.getLocations(address, addToMap);}
}); }
function addToMap(response)
{
place = response.Placemark[0];
point = new GLatLng(place.Point.coordinates[1],place.Point.coordinates[0]);
function createMarker(point,address)
{
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function()
{
map.openInfoWindowHtml(point, address);
});
return marker;
}
map.addOverlay(createMarker(point, response.name));
}

Use API v3 and in your marker setup set the tite of the marker to "name" then after adding the click listener you will be able to refer to the title of the clicked marker - if that is what you wanted.
//get your point and name whatever way you plan to do it
...
function createMarker(point,name){
var marker = new google.maps.Marker({
position: point,
map: map,
title: name,
}) ;
var content='Whatever info you want plus'+name;
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
return marker;
}
Please check the closures as I wrote it just now.
K

Related

Google Maps search - Map wont change focus from search input

Hello fellow Stackoverflow members.
I have offered to help out our local communities emergency volunteer group with an improved alert map for notifying members of incidents close by to our town.
I have been using the google maps api, along with the google places api.
I have managed to bring in their news alert JSON data, match it with their custom icons, and display it on the map successfully. However I am now struggling to get the places searchBox to update the map based on the address users are entering into the search.
NB: The search is auto-completing fine, but the map is not updating. Current error is "map.fitBounds is not a function"
My reference link which I have been using to try and get the places search integrated: https://github.com/googlemaps/js-samples/blob/737eb41e78f9cad28e2664b68450676e91424219/dist/samples/places-searchbox/inline.html
I have attached my code below. With a comment where I have added the latest edits to the code for the search function. A fresh perspective would be greatly appreciated.
UPDATE: I have compiled a JSFiddle for easier handling:
https://jsfiddle.net/mcmacca002/zvghd0nu/
Thank you and appreciated.
// BUILD GOOGLE MAPS:
var GoogleMap = {
map: null,
markers: {},
init: function(lat, lng, places) {
var self = this;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng)
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(50, 50)
});
// SEARCH STARTS HERE (ALONG WITH ISSUES):
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', function() {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
(function(place) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}(place));
}
map.fitBounds(bounds);
searchBox.set('map', map);
map.setZoom(Math.min(map.getZoom(),12));
});
// END OF SEARCH HERE.
$.each(places, function() {
self.addMarker(this);
});
this.setCenterPoint();
},
// Create map markers
addMarker: function(place) {
var self = this;
var marker = new google.maps.Marker({
position: new google.maps.LatLng(place.coordinate.latitude, place.coordinate.longitude),
map: self.map,
title: place.name,
icon: place.image
});
console.log(place);
// Create information event for each marker
marker.info_window_content = 'TEST'
self.markers[place.id] = marker
google.maps.event.addListener(marker, 'click', function() {
self.infowindow.setContent(marker.info_window_content)
self.infowindow.open(self.map, marker);
});
},
// Update map markers
updateMarkers: function(records) {
var self = this;
$.each(self.markers, function() {
this.setMap(null);
})
$.each(records, function() {
self.markers[this.id].setMap(self.map);
});
//Set map center
if (records.length) self.setCenterPoint();
},
// Set centre point for map
setCenterPoint: function() {
var lat = 0,
lng = 0;
count = 0;
//Calculate approximate center point based on number of JSON entries
for (id in this.markers) {
var m = this.markers[id];
if (m.map) {
lat += m.getPosition().lat();
lng += m.getPosition().lng();
count++;
}
}
if (count > 0) {
this.map.setCenter(new google.maps.LatLng(lat / count, lng / count));
}
}
};
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div class="container" id="map" style="height:900px;"></div>
You have an error, because you have a wrong reference to this. I updated your Jsfiddle here: https://jsfiddle.net/k23auboq/ but I will also show you what went wrong down below.
init: function(lat, lng, places) {
// ...
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', () => { // if you pass an arrow function here instead, 'this' will be taken from the outer context
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
var marker = new google.maps.Marker({
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
});
bounds.extend(place.geometry.location);
}
this.map.fitBounds(bounds); // this.map.fitBounds(...) now exists and works
searchBox.set('map', map);
this.map.setZoom(Math.min(map.getZoom(), 12));
});
// ...
},
To simplify it a bit take a look at the following examples:
function Test() {
this.map = 'test map';
this.callbackAction = function (callback) {
callback();
}
this.action = function () {
this.callbackAction(function () { // callback passed as 'function'
console.log(this.map);
});
}
return this;
}
const instance = new Test();
instance.action();
vs
function Test() {
this.map = 'test map';
this.callbackAction = function (callback) {
callback();
}
this.action = function () {
this.callbackAction(() => { // callback passed as 'ARROW function'
console.log(this.map);
});
}
return this;
}
const instance = new Test();
instance.action();
I have updated the answer which was provided above. The answer was technically correct, however using the bounds method will zoom the map down to level 1.
Here is a solution which should work for you. I have not been able to add a pin to the searched location. Hopefully somebody else may be able to help you there as I have only applied what I have learned using leaflet.js which is slightly different to Google maps, and am only still learning Javascript.
var GoogleMap = {
map: null,
markers: {},
init: function(lat, lng, places) {
var self = this;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(lat, lng),
draggable: true
};
this.map = new google.maps.Map(document.getElementById('map'), mapOptions);
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(10, 10)
});
// SEARCH STARTS HERE:
var searchBox = new google.maps.places.SearchBox(document.getElementById('pac-input'));
google.maps.event.addListener(searchBox, 'places_changed', () => {
searchBox.set('map', null);
var places = searchBox.getPlaces();
var bounds = new google.maps.LatLngBounds();
var i, place;
for (i = 0; place = places[i]; i++) {
var marker = new google.maps.Marker({
title: places.name,
zoom: 4,
position: place.geometry.location
});
marker.bindTo('map', searchBox, 'map');
google.maps.event.addListener(marker, 'map_changed', function() {
if (!this.getMap()) {
this.unbindAll();
}
bounds.extend(place.geometry.location);
});
marker.setPosition(place.geometry.location);
}
// ADDING PANTO FOR RETAINING THE MAP ZOOM LEVEL - INSTEAD OF SETZOOM :D
this.map.panTo(marker.getPosition());
});
// WHICH THEN ENABLES YOU TO REMOVE THIS:
// this.map.fitBounds(bounds);
// searchBox.set('map', map);
// this.map.setZoom(Math.min(map.getZoom(), 12));
// END OF SEARCH HERE.

How to show google map marker after x seconds without refresh google map?

How to display google map after every x seconds without google map refresh?
1.Markers latLong are coming from database.
2.Allocate that markers on google map.
3.Markers's latLong changes after 30 second.
Problem is google map get refreshed. All I want google map should display without refresh with updated LatLong.
Here is my code.
<script>
function initMap() {
var infowindow = new google.maps.InfoWindow();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
var image = '<?php echo $getImagePath; ?>'
for (var o in markers) {
lat = markers[ o ].lat;
lng = markers[ o ].lng;
address = markers[ o ].address;
var my = new google.maps.LatLng(lat, lng);
//console.log(my);
var marker = new google.maps.Marker({
position: my,
map: map,
icon: image,
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent("'" + address + "'");
infowindow.open(map, marker);
});
}
}
</script>
I tried google.maps.event.addDomListener(window, "load", initMap); and window.onload = initMap; but didn't work.
Can any one help me out?
I hope this small rewrite of your code will help you on your way. As it stands, there's a lot of information not present in the question, so I can only guess
// note these are globals because they are set in initMap and used outside of it
var image = '<?php echo $getImagePath; ?>';
var map;
var infowindow;
var markers = [/* some initially loaded markers loaded as if by majick unicorn farts */];
function initMap() {
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: 19.9518684, lng: 73.7354084}
});
doMarkers(true);
}
function doMarkers(firstLoad) {
markers.forEach(marker => {
var lat = marker.lat;
var lng = marker.lng;
marker.my = new google.maps.LatLng(lat, lng);
if (firstLoad) { // marker has no marker the first time because it's not on a map yet
marker.marker = new google.maps.Marker({
position: marker.my,
map: map,
icon: image,
});
google.maps.event.addListener(marker.marker, 'click', function () {
infowindow.setContent("'" + marker.address + "'");
infowindow.open(map, marker.marker);
});
} else { // move existing marker
marker.marker.setPosition(marker.my);
}
}
}
function magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker) {
// find corresponding marker in markers array
// update lat, lng and address
}
function doSomeAjaxToGetNewMarkerPositionsAndCallCallback(cb) {
var xhr = new XMLHttpRequest();
xhr.open('GET', 'someURI');
xhr.onload = function() {
var data = JSON.parse(xhr.responseText);
data.forEach(function(marker) {
magicallyFindAndUpdateMarkerDataUsingUnicornFarts(marker);
});
cb()
}
xhr.send();
}
setInterval(function () {
doSomeAjaxToGetNewMarkerPositionsAndCallCallback(function() {
doMarkers(false);
});
}, 30000);
Of course, I can't see how markers are loaded (into markers in your code), nor can I tell you what doSomeAjaxToGetNewMarkerPositionsAndCallCallback or magicallyFindAndUpdateMarkerDataUsingUnicornFarts should be, because you haven't shown any code regarding markers at all

Firebase & Google map - read datas and create markers. How to read object?

I am developing an application which consist in bulky wastes' signalements where each citizen could inform authorities about the place to collect them.
Datas (addresses and coordinates) are stocked into firebase and I'm working on the display of markers in a google map.
Here is the code:
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
markers: findMarkers();
console.log(markers);
console.log(markers.length);
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<p>' + 'adresse' +'</p>' + '</div>'],
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1].lat(), markers[i][1].lng());
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
function findMarkers(){
markers = [];
var data = firebase.database();
var dataRef = firebase.database().ref("signalement/");
dataRef.on("child_added", function(data) {
var key = data.key;
const signalement = data.val();
const adresse = signalement.adresse;
const coordonnees = signalement.coordonnees;
var marker = [adresse, coordonnees];
markers.push( marker );
});
// Multiple Markers
return markers;
}
</script>
</head>
<body>
<div id="map_wrapper">
<div id="map_canvas" class="mapping"></div>
</div>
</html>
Problem comes from the console.log(markers.length); which is equal to 0 ! While the previous console.log(markers); shows the object.
Maybe a syntax error of var marker?
Anyway.
Someone to help me for this case?
Thanks
Looks like the problem is with the firebase data callback. Since you have set the callback for google map api callback=initialize the marker data is not ready from the firebase by the time it executes the function.
I would rather do something like this (keeping in mind that firebase callback takes longer than the google map script being loaded & map has dependency on the data from firebase).
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "//maps.googleapis.com/maps/api/js?&callback=findMarkers";
document.body.appendChild(script);
});
function initialize(markers) {
var map;
var bounds = new google.maps.LatLngBounds();
var mapOptions = {
mapTypeId: 'roadmap'
};
// Display a map on the page
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
map.setTilt(45);
console.log(markers);
console.log(markers.length);
// Info Window Content
var infoWindowContent = [
['<div class="info_content">' +
'<p>' + 'adresse' +'</p>' + '</div>'],
];
// Display multiple markers on a map
var infoWindow = new google.maps.InfoWindow(), marker, i;
// Loop through our array of markers & place each one on the map
for( i = 0; i < markers.length; i++ ) {
var position = new google.maps.LatLng(markers[i][1].lat(), markers[i][1].lng());
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
// Allow each marker to have an info window
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infoWindow.setContent(infoWindowContent[i][0]);
infoWindow.open(map, marker);
}
})(marker, i));
}
var boundsListener = google.maps.event.addListener((map), 'bounds_changed', function(event) {
this.setZoom(14);
google.maps.event.removeListener(boundsListener);
});
}
function findMarkers(){
markers = [];
var data = firebase.database();
var dataRef = firebase.database().ref("signalement/");
dataRef.on("child_added", function(data) {
var key = data.key;
const signalement = data.val();
const adresse = signalement.adresse;
const coordonnees = signalement.coordonnees;
var marker = [adresse, coordonnees];
markers.push( marker );
});
// send prepared marker array to map initialize function
intialize(markers);
}

Google Maps API missing data from array to markers

Apologies in advance as this may seem a little complicated.
I have a Google Map Marker Array that my markers get added to called markersArray.
The details that get stored per marker are latitude, longitude, title, description.
Using the code below, it runs when a marker is clicked on my map
google.maps.event.addListener(marker, 'click', function(mll) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});
mll shows the log for the actual marker and markersArray just shows me the list of markers within the Array.
What I've noticed is that the data stored in markersArray is no being taken into the actual marker itself.
Is there a way of doing this?
If there isn't is there a way to use Javascript to find the title from the markersArray depending on the latLng values that you will see in the following image.
I screenshot what I receive when I run the Marker Click Function
Markers are added as follows using AngularJS:
$scope.createmarker = function () {
geocoder.geocode({
'address': selectedItem.gps
}, function (response, status) {
geocode_results = new Array();
geocode_results['status'] = status;
top_location = response[0];
var lat = Math.round(top_location.geometry.location.lat() * 1000000) / 1000000;
var lng = Math.round(top_location.geometry.location.lng() * 1000000) / 1000000;
geocode_results['lat'] = lat;
geocode_results['lng'] = lng;
geocode_results['l_type'] = top_location.geometry.location_type;
marker = new google.maps.Marker({
icon: mapIcon,
position: new google.maps.LatLng(lat, lng),
map: map,
title: selectedItem.title
});
markersArray.push(marker);
console.log(markersArray);
console.log(marker);
});
};
Using title instead of mll
google.maps.event.addListener(marker, 'click', function(title) {
console.log(mll);
console.log(markersArray);
var html= "<div style='color:#000;background-color:#fff;padding:5px;width:150px;'><p></p></div>";
iw = new google.maps.InfoWindow({content:html});
iw.open(map,marker);
});

Function use value in link when available

I'm unsure how to explain this properly, but I basically want to display markers via Google API on a map and have a link on them to directions to that location. However, currently it only works if the user allows their location to be tracked.
What I want to do is to have basically those markers in both situations, where user does and does not allow their location to be tracked, but just the link would be changed.
So if the user allows their location to be tracked, the link would be
var reittiohjeet = "https://www.google.fi/maps/dir/"+pos+"/"+osoite;
And if the user rejects their location to be tracked, the link would be
var reittiohjeet2 = "https://www.google.fi/maps/dir/current+location/"+osoite;
I tried creating alternative function that would be ran in the if(navigator.geolocation)'s else clause, but that didn't seem to do anything at all.
function initialize() {
var mapOptions =  {
center: new google.maps.LatLng(60.174,24.927),
zoom: 8
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
// Luo marker
var image = 'user-location.png';
var userMarker = new google.maps.Marker({
position: pos,
map: map,
icon: image
});
map.setCenter(pos);
setMarkers(map, shops, pos);
}, function() {
handleNoGeolocation(true);
});
} else {
handleNoGeolocation(false);
}
}
function setMarkers(map, locations, pos) {
for (var i = 0; i < locations.length; i++) {
var shop = locations[i];
var myLatLng = new google.maps.LatLng(shop[1], shop[2]);
var nimi = shop[0];
var osoite = shop[5];
var puhelinnumero = shop[3];
var verkkosivu = shop[4];
var reittiohjeet = "https://www.google.fi/maps/dir/"+pos+"/"+osoite;
var content = "<div class='content'><h3>"+nimi+"</h3><strong>Osoite:</strong> "+osoite+"<br /><strong>Puhelinnumero:</strong> "+puhelinnumero+"<br /><strong>Verkkosivu:</strong> <a href='"+verkkosivu+"' target='_blank'>"+verkkosivu+"</a><br /><br /><a href='"+reittiohjeet+"'>Reittiohjeet</a></div>";
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: shop[0]
});
var infowindow = new google.maps.InfoWindow()
google.maps.event.addListener(marker,'click', (function(marker,content,infowindow){
return function() {
infowindow.setContent(content);
infowindow.open(map,marker);
};
})(marker,content,infowindow));
}
}
The statement in the else-clause will only be executed when the browser doesn't support geolocation.
When the user denies access the function defined as 2nd argument of getCurrentPosition will be executed.
Note: in Firefox this will not work as expected, see: Firefox 11 and GeoLocation denial callback

Categories

Resources