Google maps api with infowindow not working - javascript

I'm trying to create a map with info windows that open with the user clicks on a marker. So far the code doesn't seem to be working, the map was displaying before but once I put in the code for the info window pop-ups not only did the info window not show but the map also stopped showing on my webpage. Here's the code:
<div id= "map"> </div>
<script>
var map;
var markers=[];
function initMap(){
map= new google.maps.Map(document.getElementById('map'),{
center:{ lat:40.7413549, lng:-73.9980244},
zoom:13
});
var locations=[
{title:"Park Ave Penthouse",location:{lat:40.7713024,lng:-73.9632393}},
{title:"Chelsea Loft", location;{lat:40.7444883,lng:-73.9949465}},
{title:"Union Square Open Floor Plan",location:{lat:40.7347062,lng:-73.984377}},
{title:"East Village Hip Studio",location:{lat:40.7281777,lng:-73.984377}},
{title:"TriBeCa Artsy Bachelor Pad",location:{lat:40.7195264,lng:-74.0089934}},
{title:"Chinatown Homey Space",location:{lat:40.7180628,lng:-73.9961237}}
];
var largeInfowindow= new google.maps.InfoWindow();
var bounds= new google.maps.LatLngBounds();
for (var i=0; i< locations.lenght;i++){
var position = locations[i].location;
var title = locations[i].title;
var marker= new google.maps.Marker({
map: map,
position:position,
title:title,
animation:google.maps.Animation.Drop,
id:i
});
markers.push(marker);
bounds.extend(marker.position);
marker.addListner ("click",function(){
populateInfoWindow(this,largeInfowindow);
});
map.fitBounds(bounds);
};
markers.push(marker);
markers.addListner("click",function(){
populateInfoWindow(this,largeInfoWindow);
});
}
function populateInfoWindow (marker, infowindow){
if(infowindow.marker=!marker){
infowindow.marker= marker;
infowindow.setContent("<div>"+marker.title+"</div>");
infowindow.open(map,marker);
infowindow.addListner("closeclick",function(){
infowindow.setMarker(null);
});
}
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyAvrWT4KKcsDSSGYXpxRry3m7j90pPjZgA&v=3&callback=initMap"></script>

The error is in this line:
if(infowindow.marker=!marker){ //it is "!=" and not "=!"
Always check console for javascript errors. After infowindow code, you could not even see the mao which means you have javascript errors.

Related

Multiple markers working on my local server but markers not working on my live site. http://www.sierracrestweb.com/dev/

Here is the code below, Perfectly display the purple icon on my local server but markers not shown on my website, I search on google and try alternate method but still facing this problem, I guess it is due to Multiple loading API Key errors, but if this How to resolve this error? because I already remove all the script but still face the problem.
<script>
var map;
var marker;
var infowindow;
var red_icon = 'http://maps.google.com/mapfiles/ms/icons/red-dot.png' ;
var purple_icon = 'http://maps.google.com/mapfiles/ms/icons/purple-dot.png';
var locations = <?php get_all_locations() ?>;
function initMap() {
var america = {lat: 37.09024, lng: -95.712891};
infowindow = new google.maps.InfoWindow();
map = new google.maps.Map(document.getElementById('map'), {
center: america,
zoom: 7
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
var i ;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i]
[2]),
icon : purple_icon,
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
<script async defer
src="https://maps.googleapis.com/maps/api/js?
language=en&key=APIKEY&callback=initMap">
</script>
If the marker creation is working on your local but not on server then it is probably not related to the code itself.
I think that the issue is with this line.
var locations = <?php get_all_locations() ?>;
Most likely this function is returning a blank array due to which no markers are plotted on the map.
Try printing out the value of the returned array in the console to ensure that you are indeed getting the correct location array.
var locations = <?php get_all_locations() ?>;
console.log(locations);

Google Maps API loads from html file, but not on local host

I am trying to connect to the Google Maps API from a localhost through an AngularJS application but the map does not appear and the map request does not reach google. The javascript file is being found by the html, and test1 is being outputted in the console, but initMap is not being called and test2 is not outputted. I expect that it is failing because a https connection is not being made to Google.
When I open the html file in a browser, the map loads fine but when I run it on my localhost, nothing comes up.
Here is my html code:
<script src="client/services/maps.client.services.map.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key={{API_KEY}}&callback=initMap"></script>
and javascript (map.js):
console.log('test1');
function initMap() {
console.log('test2');
//Markers
var markers = [
['Cardiff', 51.4539, -3.1694, 'city/cardiff'],
['Swansea', 51.6148, -3.92927895, 'city/swansea']
];
// Initialise map
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: {lat: 51.4539, lng: -3.1694}
});
var bounds = new google.maps.LatLngBounds();
for( i = 0; i < markers.length; i++ ) {
// Plot pin for each place
var position = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
window.location.href = markers[i][3];
}
})(marker, i));
}
// Zoom so all pins are in view
map.fitBounds(bounds);
}
Does anyone understand why the initMap function is not being called?
change the order of the script tags
<script src="https://maps.googleapis.com/maps/api/js?key={{API_KEY}}&callback=initMap"></script>
<script src="client/services/maps.client.services.map.js"></script>

Cannot seem to get marker clicks on Google Maps to do anything

I have a simple Google Maps feat I'm trying and failing to accomplish.
Presently, I can display my map, then cycle through a list of Projects via PHP (I'm using ExpressionEngine), and add each project's latitude/longitude to a JavaScript array.
Once the values are in the JavaScript array, I use jQuery to cycle through each one, and add a marker to the map.
I'm able to click the map and have it respond appropriately; however, when I attempt to click one of the markers, nothing happens at all.
I have tried moving code, renaming, changing, editing, and tweaking endlessly... I cannot figure this out. Any help at all would be hugely appreciated. My code is as follows:
<script>
// Create the new map_locations array
var map_locations = [];
</script>
<!-- The following ExpressionEngine script loops through all the 'projects' on the site,
then pushes each project to the map_locations array. -->
{exp:channel:entries channel="projects"}
<script>
map_locations.push( ['{url_title}', '{project_latitude}', '{project_longitude}', '{categories}{category_name}{/categories}', '{title}'] );
</script>
{/exp:channel:entries}
<script>
var marker;
function initialize() {
// To add the marker to the map, use the 'map' property
var mapOptions = {
center: { lat: 51.884 , lng: -95.147 },
zoom: 4
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
// Create a new location lat/long var, newLatLng
var newLatLng;
var contentString = "<div id='info_window'>this is the info window</div>"
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var iconBase = '/images/map_icon_';
$.each( map_locations, function()
{
newLatLng = new google.maps.LatLng( this[1] , this[2] );
marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
});
google.maps.event.addListener(marker, 'click', function() {
console.log( "This marker's url_title is: " + this[0] );
});
google.maps.event.addListener(map, 'click', function() {
console.log( "Testing map click" );
});
}
// Initialize the map
google.maps.event.addDomListener(window, 'load', initialize);
</script>
You are trying to add event listener for markers after the loop where marker gets defined rather than in the loop
Try:
$.each( map_locations, function(){
var newLatLng = new google.maps.LatLng( this[1] , this[2] );
var marker = new google.maps.Marker({
position: newLatLng,
map: map,
title: this[4],
icon: iconBase + this[3]
});
google.maps.event.addListener(marker, 'click', function(marker) {
console.log( "This marker's url_title is: " + marker.title );
});
});

Google maps API recenter my map

My code for the initialization of the API looks like so:
jQuery(function($) {
// Asynchronously Load the map API
var script = document.createElement('script');
script.src = "http://maps.googleapis.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
});
function initialize() {
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);
// Multiple Markers
var markers = [
//php code to get markers from DB
];
// Info Window Content
var infoWindowContent = ['some text here'];
// 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], markers[i][2]);
bounds.extend(position);
marker = new google.maps.Marker({
position: position,
map: map,
title: markers[i][0]
});
//push markers to mapMarkers array.
mapMarkers.push(marker);
// 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));
// Automatically center the map fitting all markers on the screen
map.fitBounds(bounds);
}
}
Problem is I dont want the map to be centered around my markers I get from the database anymore. But if I delete map.fitBounds(bounds); and try to use map.setCenter({lat: -34, lng: 151}); I get a blank screen. If I even touch anything in this code I get a blank screen instead of my map!
A map must have a zoom.
You didn't initially set a zoom for the map.
When you use fitBounds() the zoom will be set automatically, but when you didn't use it the zoom is still missing.
Solution: set a zoom in mapOptions

Google Maps DomListener Causing Error After Going to Different Page

I am having an issue where the dom listener at the bottom of my google maps function in an external Javascript file is causing a "google is not defined" console error. This happens when I go to a different HTML page on my website that also accesses script in the external file. I believe it is because the DomListener is outside the function however the function does not work if the dom listener is inside the function. Can someone please help me with where to put this DomListener to stop this error occurring? My code is below.
Thankyou very much,
Anthony
function validateEmail() {
var email = form.emailaddress.value;
if (form.firstname.value == "") {
document.getElementById("emailInvalid").style.visibility = "visible";
return false;
} return true;
}
function initialize() {
var myLatlng1 = new google.maps.LatLng(-25.363882,150.044922);
var myLatlng2 = new google.maps.LatLng(-25.363882,152.044922);
var mapOptions = {
zoom: 6,
center: myLatlng1
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var contentString1 = 'Mott Park'
var contentString2 = 'Kilpa Park'
var infowindow = new google.maps.InfoWindow({
});
var marker1 = new google.maps.Marker({
position: myLatlng1,
map: map,
title: 'Park'
});
var marker2 = new google.maps.Marker({
position: myLatlng2,
map: map,
title: 'Water'
});
google.maps.event.addListener(marker1, 'click', function initialize() {
infowindow.close();//hide the infowindow
infowindow.setContent(contentString1);//update the content for this marker
infowindow.open(map, marker1);
});
google.maps.event.addListener(marker2, 'click', function initialize() {
infowindow.close();//hide the infowindow
infowindow.setContent(contentString2);//update the content for this marker
infowindow.open(map, marker2);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
Here a possible duplicate:
"google is not defined" when using Google Maps V3 in Firefox remotely
I think its might be a placement problem similar to Diego Pino in the thread.

Categories