I am trying to create an infowindow that shows a piece of text 'this is my marker' when the map is loaded but it is not showing. I'm using the exact same code from my lecturer's powerpoint but idk where I'm going wrong.
function initialize(){
let mapDiv = document.getElementById('map');
let mapOptions = {
center: new google.maps.LatLng(Coords.lat,Coords.lng),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
let marker = new google.maps.Marker({
position: new google.maps.LatLng(40.72,-74.00),
map: map,
title: 'I am here!',
icon: svgMarker
});
var infoWindow = new google.maps.InfoWindow({content: 'This is my marker'});
google.maps.event.addListener(marker, 'click', function()
{
infoWindow.open(map,this);
});
map = new google.maps.Map(document.getElementById("map"), mapOptions);
};
You have the sequence slightly wrong. You are attempting to add both the marker & the infoWindow before you have created the map. Perhaps if you re-sequence your code a little like this:
/* assumed that a global variable exists */
let Coords={
lat:41,
lng:-75
};
function initialize(){
let options = {
center: new google.maps.LatLng( Coords.lat,Coords.lng ),
zoom: 4,
mapTypeId: google.maps.MapTypeId.HYBRID
};
let map = new google.maps.Map( document.getElementById("map"), options );
let marker = new google.maps.Marker({
position: new google.maps.LatLng(40.72,-74.00),
map: map,
title: 'I am here!'
/*,
icon: svgMarker
*/
});
let infoWindow = new google.maps.InfoWindow( { content:'This is my marker' } );
infoWindow.open( map, marker );
google.maps.event.addListener(marker, 'click', function(e) {
infoWindow.open(map,this);
});
};
To get the infoWindow to appear when the map is loaded you should call the open method and if you supply the previously created marker as the second argument it will appear in the correct location.