I am trying to implement a rating system inside the infowindow on Google Maps API version 3.
I tried both Rateit and Raty and I coudn't make neither of them work.
I tried this code here and it doesn't work for me:
function initialize() {
var mapOptions = {
zoom: 5,
center: new google.maps.LatLng(2, 2),
mapTypeId: google.maps.MapTypeId.ROADMAP
},
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions),
locations = [
[null, 1, 1, 'title#1', null, null, 1.3, 'foo'],
[null, 2, 2, 'title#2', null, null, 3.7, 'bar'],
[null, 3, 3, 'title#3', null, null, 4.3, 'boofar']
],
infowindow = new google.maps.InfoWindow(),
i;
//use the domready-event of the infowindow to execute $.raty
google.maps.event.addListener(infowindow, 'domready', function() {
$(this.getContent()).find('.stars').raty({
half: true,
score: function() {
return $(this).attr('data-score');
},
readOnly: true,
path: 'https://raw.githubusercontent.com/wbotelhos/raty/master/demo/images/'
});
});
for (i = 0; i < locations.length; i++) {
(function(location) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[1], location[2]),
title: location[3],
map: map,
info: $('<div/>')
//the rating
.append($('<div class="stars"></div>').attr('data-score', location[6]))
//review-link
.append($('' + locations[i][7] + ' reviews'))
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(this.info[0]);
infowindow.open(map, this);
});
}(locations[i]))
}
}
google.maps.event.addDomListener(window, 'load', initialize);
Here is my code and what I have done so far.
Scripts:
<!-- Load libraries -->
<script src="js/jquery-1.12.1.min.js"></script>
<script src="js/jquery.raty.js"></script>
<!-- Google Maps API tag -->
<script src="https://maps.googleapis.com/maps/api/js?v=3">
</script>
<script type="text/javascript">
window.addEventListener("load",function() {
// Set a timeout...
setTimeout(function(){
// Hide the address bar!
window.scrollTo(0, 1);
}, 0);
});
$('.search-box,.menu' ).hide();
$('.options li:first-child').click(function(){
$(this).toggleClass('active');
$('.search-box').toggle();
$('.menu').hide();
$('.options li:last-child').removeClass('active');
});
$('.options li:last-child').click(function(){
$(this).toggleClass('active');
$('.menu').toggle();
$('.search-box').hide();
$('.options li:first-child').removeClass('active');
});
$('.content').click(function(){
$('.search-box,.menu' ).hide();
$('.options li:last-child, .options li:first-child').removeClass('active');
});
</script>
<!-- Google Maps Script -->
<script type="text/javascript">
function initMap() {
// Create a map object and specify the DOM element for display.
var zoomlevel = 10;
var abudhabi = {lat:24.373368, lng:54.488754};
var map = new google.maps.Map(document.getElementById('map'), {
center: abudhabi,
scrollwheel: false,
zoom: zoomlevel
});
// Load up markers with their labels and infos.
//Test variables:
var locations = [
['McGettigan \'s Irish Pub',24.438533,54.572991,2],
['Cooper\'s',24.4238,54.473619,3]
];
var infowindow = new google.maps.InfoWindow();
//on infowindow load -> read data and display stars
google.maps.event.addListener(infowindow, 'domready', function() {
$(this.getContent()).find('.stars').raty({
score: function() {
return $(this).attr('data-score'); // THIS DOESN'T RETURN ANY VALUE...
},
readOnly: true,
path: 'images/' //this is my path for the images, they are fine...
});
});
for (var i=0; i<locations.length; i++){
(function(location){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[1], location[2]),
title: location[0],
map: map,
info: $('<div/>')
.append($('<div class="stars"></div>').attr('data-score', location[3]))
});
// Add event listener on marker -> open info
google.maps.event.addListener(marker, 'click',function(){
infowindow.setContent(this.info[0]);
infowindow.open(map,this);
});
})(locations[i])
}
}
google.maps.event.addDomListener(window,'load',initMap);
</script>
The raty.js is returning (line 1 error):
Error: Invalid selector!
Really appreciate the help, I am new in javascript and jquery. I tried hard but I coudn't figured out the reason why is not working.
Thank you in advance.
Found my mistake: Rateit script was working before I insert the div tag for it to read. I missed a basic concept here. Solution was like this:
var infowindow = new google.maps.InfoWindow();
//on infowindow load -> read data and display stars
google.maps.event.addListener(infowindow, 'domready', function() {
$("#info").rateit(); //HERE IS THE TRICK (CALL RATEIT AGAIN)
});
for (var i=0; i<locations.length; i++){
(function(location){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(location[1], location[2]),
title: location[0],
map: map,
});
// Add event listener on marker -> open info
google.maps.event.addListener(marker, 'click',function(){
var content = '<div class="rateit"'+
' data-rateit-value="'+ location[3] +
'" data-rateit-ispreset="true" data-rateit-readonly="true"'+
' id="info"></div>';
infowindow.open(map,this);
infowindow.setContent(content);
});
})(locations[i])
}
In any case, I still couldn't make raty work. Everytime I called it inside 'domready' event tons of stars appeared and score function never returned the attribute 'data-score'..
Anyway I found another way so it's fine for now.
Thanks.
Related
Not the best with javascript and got some trouble with some google maps code but it is sporadic on MS Edge but consistent on Chrome and the markers will not load. On edge if you keep request the page sometimes it works but more than often fails.
ERROR: not a LatLngBounds or LatLngBoundsLiteral: not an Object name:
"InvalidValueError"
script is called using below code
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=XXXXXXXXXXXXXXXXXXXXXX&libraries=places"></script>```
<script async type="text/javascript" src="{{media url='scripts/store-locator.js'}}"></script>```
require(["jquery"], function ($) {
$(document).ready(function () {
initialize();
});
var geocoder,
map,
markers = [],
infowindow = new google.maps.InfoWindow(),
bounds = new google.maps.LatLngBounds(),
marker, i;
var locations = [
{ id: 1, name: 'Store1', lat: 58.482514, lng: -1.784622 },
{ id: 2, name: 'Store2', lat: 54.687925, lng: 0.312584 }
];
function initialize() {
// set the default google map settings
geocoder = new google.maps.Geocoder();
directionsDisplay = new google.maps.DirectionsRenderer({ draggable: true });
var latlng = new google.maps.LatLng(52.727440, -1.543299);
var myOptions = {
zoom: 6,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// register the google map elements
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
// register the directions display
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('directions'));
addMarkers();
map.fitBounds(bounds);
google.maps.event.addListenerOnce(map, 'tilesloaded', function () {
// setup control position
control = document.getElementById('store-selector');
map.controls[google.maps.ControlPosition.TOP_RIGHT].push(control);
control.style.display = 'block';
});
}
// add the markers from the array to the map
function addMarkers() {
$.each(locations, function (key, value) {
// create the marker
marker = new google.maps.Marker({
position: new google.maps.LatLng(this.lat, this.lng),
map: map,
name: this.name
});
// add the marker to the cached array
markers.push(marker);
bounds.extend(marker.position);
// add the event listerner for the marker click function
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
// info window display
map.setZoom(16);
map.setCenter(marker.getPosition());
}
})(marker, i));
});
}
});```
Ok I think I have resolved it thanks to geocodezip who suggested a timing issue. was erroring on $(document).ready(function () {
initialize();
});
I've moved this to the bottom of the file and it seems to be running all good now..
I have this google map which is working, I want to add a button on infowindow which somehow is not working. Though the function is defined but still throw error
http://jsfiddle.net/mpgxn53q/
<div id="apptMap"></div>
//the js code
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
var locations = [["158845-001 - Adas Israel Congregation",38.9369545,-77.0575097,1],["163888-137 - Construction LLC",43.1765812,-84.6986701,2.0],["163888-155 - Construction LLC",43.1765812,-84.6986701,3.0],["167176-007 - GLDB MTM10 GLR016",42.4894512,-95.5449508,4.0],["167195-003 - 91622 DB A4",42.8275053,-84.5717997,5.0],["167195-002 - 91622 DB A4",42.8275053,-84.5717997,6.0],["167176-005 - GLDB MTM10 GLR016",42.0023,-93.6110955,7.0],["167176-004 - GLDB MTM10 GLR016",42.0023,-93.6110955,8.0]];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('apptMap'), {
zoom: 10,
center: new google.maps.LatLng(42.0023,-93.6110955),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>',
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
function mapsZoomMarker(wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
init();
There is a problem with scopes, and that's because of that how you wrote your script. I am not going to rewrite your script, but I will give you solution for your exact situation.
You need to define your function mapsZoomMarker in global scope (window object) like this:
window.mapsZoomMarker = function (wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
And there is also a mistake, in the function which is called when the marker is clicked. When you assign the html for the popup like this
content: this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>'
the i variable is already set to 8, so instead of that just use this.id like this:
content: this.html +'<button onclick="mapsZoomMarker('+this.id+')">Click me</button>'
And this is the updated fiddle http://jsfiddle.net/rn27f05v/
I will propose a solution that I think is best for what you want. Instead call function inside var infowindow, you can only define a variable to put content your want.
You can change you var infowindow to:
var infowindow = new google.maps.InfoWindow({
id: this.id,
content: content, //here the variable that call your content
position:this.getPosition()
});
So... above your google.maps.event.addListener(markers[i], 'click', function(){... you can add:
var content = '<button onclick="mapsZoomMarker('+i+')">Click me</button>';
This way the click action will work.
Hope this tip help you.
I have a map with streetview panorama, an infowindow and a draggable marker. After the marker is dragged, a function requests the getPanoramaByLocation to see whether the view service is available. If it's not, it closes the infowindow. That is great but when I click again on the marker the infowindow does not open anymore. Do you know what is wrong please?
tx
var sv = new google.maps.StreetViewService();
function initialize() {
var optionMap = {
zoom: 13,
center: new google.maps.LatLng(47.390251,0.68882),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myMap = new google.maps.Map(document.getElementById("mapDiv"), optionMap);
var optionsMarker = {
position: new google.maps.LatLng(47.390251,0.68882),
map: myMap,
draggable: true,
title: "my marker"
}
var marker = new google.maps.Marker(optionsMarker);
var infowindowDiv = '<div id="streetview" style="width:300px;height:200px;"' +'</div>';
var infoWindow = new google.maps.InfoWindow({
content: infowindowDiv,
position: myMap.getCenter() });
google.maps.event.addListener(marker, 'click', function() {
infoWindow.open(myMap, marker);
});
google.maps.event.addListener(infoWindow, 'domready', function() {
var panorama = new
google.maps.StreetViewPanorama(document.getElementById("streetview"));
panorama.setPosition(infoWindow.getPosition());
google.maps.event.addListener(marker, 'dragend', function(event) {
sv.getPanoramaByLocation(event.latLng, 50, processSVData);});
function processSVData(data, status) {
if (status == google.maps.StreetViewStatus.OK) {
var markerPanoID = data.location.pano;
// Set the Pano to use the passed panoID
panorama.setPano(markerPanoID);
panorama.setPov({
heading: 270,
pitch: 0,
zoom: 1
});
panorama.setVisible(true);
}
else {
infoWindow.close();
infoWindow = null;
};
}
});
}
From the GMaps API docs:
close() None Closes this InfoWindow by removing it from the DOM structure.
https://developers.google.com/maps/documentation/javascript/reference#InfoWindow
So... If you close the infowindow, it's gone. For ever. All the more so if you REALLY make sure it's gone by saying "infoWindow = null;" You have to make a new one. My advice would be to refactor your code to have a separate function that creates the infowindow on demand and returns it. In your click event definition, check whether infowindow is null, and if so, grab a new one.
HTH
As the other answer explain, the infobox html is removed from DOM when the user clicks the close button, but the JS object still there.
When you create an infowindow you must call the open method to see it on the map
myInfoWindow.open(mymap);
So, if you listen to the 'closeclick' event and keep the infowindow state
var infoWindowClosed = false;
google.maps.event.addListener(myInfoBox, "closeclick", function () {
infoWindowClosed = true;
});
you can reopen myInfoWindow on demand
if(infoWindowClosed){
myInfoWindow.open(mymap);
}
My marker will always displays the last info on click of it. Basically I want to display the corresponding info for each of the clicked markers. here is what I have so far:
$(function() {
var map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom : 2,
center: new google.maps.LatLng(43.65654, -79.90138),
mapTypeControl: false, //will remove the top right corner Map type(Satellite/Map)
//scaleControl: false,
navigationControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
$.get('example.xml', function(xml) {
$('marker',xml).each(function(i) {
var $this = $(this),
the_marker = new google.maps.Marker({
title: $this.find('label').text(),
map: map,
clickable: true,
position: new google.maps.LatLng(
parseFloat($this.find('lat').text()),
parseFloat($this.find('lon').text())
)});
new google.maps.event.addListener(the_marker, 'click', function() {
getInfo();
});
});
});
function getInfo() {
$.ajax({
type:'GET',
url:'example.xml',
dataType:'xml',
success: function(xml) {
$(xml).each(function() {
$(this).find("marker").each(function() {
$(this).find("info");
$("#newDiv").html($(this).find("info"));
})
})
}
})
$("#newDiv").html($(this).find("info").text());
}
});
It is like I am getting always the last infowindow on click of my markers, but rather i want the each marker to have its own infowindow open. Now I dont have infowindow's in my example and i have divs in it.
Thanks
You can simply use array to do it.
like,
markers[i] = new Marker({ some options });
new google.maps.event.addListener(markers[i], 'click', function() {
getInfo(i);
});
added:
still cannot get why'd you like to get only first marker in xml on click of any markers.
any demo or example?
if you wanna fetch the info of clicked marker, do it like this.
markers[i] = new Marker({ some options });
info[i] = $(this).find('info');
new google.maps.event.addListener(markers[i], 'click', function() {
$("#newDiv").html(info[i]);
});
I'm trying to add infoWindow's to multiple markers on a Google Map. The closest I have come is to get an infoWindow to display the last address you can see in the array, on all markers. The bit of code I have pasted below does not work, I get an "Uncaught TypeError: Cannot read property '4' of undefined". I'm sure this is a scope issue, but I'm going round in circles here and could do with some help:
var hotels = [
['ibis Birmingham Airport', 52.452656, -1.730548, 4, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3AW','(+44)1217805800','(+44)1217805810','info#ibisbhamairport.com','http://www.booknowaddress.com'],
['ETAP Birmingham Airport', 52.452527, -1.731644, 3, 'Ambassador Road<br />Bickenhill<br />Solihull<br />Birmingham<br />B26 3QL','(+44)1217805858','(+44)1217805860','info#etapbhamairport.com','http://www.booknowaddress.com'],
['ibis Birmingham City Centre', 52.475162, -1.897208, 2, 'Ladywell Walk<br />Birmingham<br />B5 4ST','(+44)1216226010','(+44)1216226020','info#ibisbhamcity.com','http://www.booknowaddress.com']
];
for (var i = 0; i < hotels.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(hotels[i][1], hotels[i][2]),
map: map,
icon: image,
title: hotels[i][0],
zIndex: hotels[i][2]
});
var infoWindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function () {
var markerContent = hotels[i][4];
infoWindow.setContent(markerContent);
infoWindow.open(map, this);
});
}
Thanks in anticipation.
We've solved this, although we didn't think having the addListener outside of the for would make any difference, it seems to. Here's the answer:
Create a new function with your information for the infoWindow in it:
function addInfoWindow(marker, message) {
var infoWindow = new google.maps.InfoWindow({
content: message
});
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
}
Then call the function with the array ID and the marker you want to create:
addInfoWindow(marker, hotels[i][3]);
Although this question has already been answered, I think this approach is better :
http://jsfiddle.net/kjy112/3CvaD/ extract from this question on StackOverFlow google maps - open marker infowindow given the coordinates:
Each marker gets an "infowindow" entry :
function createMarker(lat, lon, html) {
var newmarker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lon),
map: map,
title: html
});
newmarker['infowindow'] = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(newmarker, 'mouseover', function() {
this['infowindow'].open(map, this);
});
}