Google maps - Custom JS to output infowindows and markers issues - javascript

Trying to simplify my google maps custom code to put markers and an info bubble. However have run into a few issues which I can't seem to debug the code is below, it's currently outputting nothing. The code defines lat/long/title and content and then trys to ouput them as markers on a map.
<script type="text/javascript">
function initialize() {
var myLatlng = new google.maps.LatLng(20,0);
var myOptions = {
zoom: 2,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var countries = [
{title:'Afghanistan', lat:34.28, lon:69.11, content:"<h2>Afghanistan</h2><p>16 Alumni</p>"},
{title:'Albania', lat:41.18, lon:19.49, content:"<h2>Albania</h2><p>7 Alumni</p>"},
{title:'Angola', lat:-8.5, lon:13.15, content:"<h2>Angola</h2><p>9 Alumni</p>"},
{title:'Antarctica', lat:-80, lon:0, content:"<h2>Antarctica</h2><p>1 Alumnus</p>"},
{title:'Antigua & Barbuda', lat:17.20, lon:-61.48, content:"<h2>Antigua & Barbuda</h2><p>1 Alumnus</p>"},
{title:'Argentina', lat:-36.30, lon:-60, content:"<h2>Argentina</h2><p>29 Alumni</p>"},
];
for (i=0;i<countries.length;i++)
{
c = countries[i];
marker: new google.maps.Marker({position: new google.maps.LatLng(" + c['lat'] + "," + c['lon'] + "), map: map, title: '" + c['title'] + "'}),
infowindow: new google.maps.InfoWindow({content: '" + c['content'] + "'});
}
var item;
for (var i=0; i<countries.length; i++) {
item = countries[i];
google.maps.event.addListener(item.marker, 'click', makeCallback(item));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}
}
</script>

There are various typographical and syntax errors in the code. Also there is no need to construct strings in the place of variables. The following is a working version:
...
var countries = [...];
for (var i = 0; i < countries.length; i++) {
var c = countries[i];
c.marker = new google.maps.Marker({
position: new google.maps.LatLng(c.lat, c.lon),
map: map,
title: c.title});
c.infowindow = new google.maps.InfoWindow({content: c.content});
google.maps.event.addListener(c.marker, 'click', makeCallback(c));
}
function makeCallback(country) {
return function () {
country.infowindow.open(map, country.marker);
};
}

Related

Removing all showed marks Google API

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>

google maps Cannot read property 'maps' of undefined

i trying to display markers according to user location and i keep getting this error that as commenas it is i didnt find any solution that match my problem,
thae error i'm getiing is : Uncaught TypeError: Cannot read property 'maps' of undefined & its referring to this :at Array.filter (native) .
thanks:
<script src="https://maps.googleapis.com/maps/api/js?key="My_Api_Key"&libraries=geometry"></script>
<script>
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var userLatLng = currentLatitude + currentLongitude;
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() { return map; }
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
</script>
https://jsfiddle.net/1gm0u4wd/9/
Your html will be as below. Your maps api javascript will be linked inside html section not javascript section.
<div id="map" style="width: 500px; height: 500px"/>
<script src="https://maps.googleapis.com/maps/api/js?key=yourMapsAPIKey&libraries=geometry"></script>
Note : "yourMapsAPIKey" should be your API key.
You can get your maps api key from here.
Update your script as below
"use strict";
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(
function(position) {
var currentLatitude = position.coords.latitude;
var currentLongitude = position.coords.longitude;
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: new google.maps.LatLng(currentLatitude, currentLongitude),
});
//your dynamic markers
var markers = #Html.Raw(Json.Encode(Model.UpcomingLectureGigs));
//default marker at current location
//var markers = new google.maps.Marker({
//position: new google.maps.LatLng(currentLatitude, currentLongitude),
//map: map,
//title: 'Hello World!'
//});
var userLatLng = new window.google.maps.LatLng(currentLatitude, currentLongitude);
//your filter function
var markersFiltered = markers.filter(function(markers, index, array, google) {
var myLatlng = new window.google.maps.LatLng(markers.Latitude, markers.Longitude);
return google.maps.geometry.spherical.computeDistanceBetween(userLatLng, myLatlng) < 10000;
});
window.onload = function(a) {
var mapOptions = {
center: new window.google.maps.LatLng(markers[0].Latitude, markers[0].Longitude),
zoom: 8,
mapTypeId: window.google.maps.MapTypeId.ROADMAP
};
var infoWindow = new window.google.maps.InfoWindow();
var map = new window.google.maps.Map(document.getElementById("dvMap"), mapOptions);
for (var i = 0; i < markersFiltered.length; i++) {
var data = markers[i];
var myLatlng = new window.google.maps.LatLng(data.Latitude, data.Longitude);
var marker = new window.google.maps.Marker({
position: myLatlng,
draggable: true,
animation: google.maps.Animation.DROP,
get map() {
return map;
}
});
(function(marker, data) {
window.google.maps.event.addListener(marker,
"click",
function(e) {
infoWindow.setContent(data.Venue + " " + data.Genre.Name);
infoWindow.open(map, marker);
});
})(marker, data);
}
};
});
};
Fiddle here

Multiple "InfoWindow" for array of "markers" on Google Maps?

Using Google Maps API to add an infoWindow to each marker. Markers come from an array.
Although, infoWindow only shows up for the first marker, not the others. Why? Thanks.
function set_markers(array) {
var mapOptions = {
zoom: 13
}
for (var i = 0; i < array.length; i++) {
var single_location = array[i];
var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: single_location[0]
});
var infowindow = new google.maps.InfoWindow({
content: ""
});
}
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<h3>'+this.title+'</h3>');
infowindow.open(map,this);
});
}
var infowindow = new google.maps.InfoWindow();
function set_markers(array) {
var mapOptions = {
zoom: 13
};
for (var i = 0; i < array.length; i++) {
var single_location = array[i];
var myLatLng = new google.maps.LatLng(single_location[1], single_location[2]);
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: single_location[0]
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent('<h3>' + this.title + '</h3>');
infowindow.open(map, this);
});
}
}
This is untested since you didn't post a MCVE.

google maps infowindow positioning with polylines

I have a map with multiple polylines which I am looking to display infowindow for each line. I have the infowindow working but it is not positioning to the event click as it should be. Instead, each window displays in the same place. Can't seem to track down the root of the issue.
<script type="text/javascript">
var contentString = "";
var infowindow = new google.maps.InfoWindow({
content: contentString,
});
function initialize() {
var myLatlng = new google.maps.LatLng(30.695895, -97.354080);
var mapOptions = {
zoom: 5,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.TERRAIN,
};
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
downloadUrl("data.xml", function(data) {
var xml = xmlParse(data);
var polylines = xml.documentElement.getElementsByTagName("polyline");
var polylineData = new Array();
for (var i = 0; i < polylines.length; i++) {
polylineData[i] = {id:polylines[i].getAttribute("id"),
name:polylines[i].getAttribute("name"),
olat:polylines[i].getAttribute("olat"),
olng:polylines[i].getAttribute("olng"),
dlat:polylines[i].getAttribute("dlat"),
dlng:polylines[i].getAttribute("dlng")}
}
for (var j = 0; j < polylineData.length; j++) {
var path = [
new google.maps.LatLng(parseFloat(polylineData[j].olat), parseFloat(polylineData[j].olng)),
new google.maps.LatLng(parseFloat(polylineData[j].dlat), parseFloat(polylineData[j].dlng))
];
var polyline = new google.maps.Polyline({
path: path,
strokeWeight: 2
});
google.maps.event.addListener(polyline, 'click', (function(event,index){
return function(){
infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
var point = event.latLng;
infowindow.setPosition(point);
infowindow.open(map);
};
})(event,j));
polyline.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
XML data looks like this:
<polylines>
<polyline id="176" name="Line Name" olat="53.545204" olng="-113.369492" dlat="53.545204" dlng="-113.369492"/>
</polylines>
I have read some similar posts but none of the answers have worked in this case thus far. Thanks!
event must be the argument passed to the returned function:
google.maps.event.addListener(polyline, 'click', (function(index){
//_________________________________________________________^:the index of the item
return function(event){
//________________^:the event
infowindow.content = '<div class="infobox" style="width:280px;"><span class="name">' + polylineData[index].name + '</span></div>';
var point = event.latLng;
infowindow.setPosition(point);
infowindow.open(map);
};
})(j));

Google maps v3 array marker

Hy i am unable to display multiple markers in Google Maps V3, i am getting the coordinates correctly but not displays on map. Also no errors in console
map_items[0] = title
map_items[1] = 55.153766, 11.909180
map_items[2] = link
map_items[3] = text
all of them appear correctly if i do an alert.
example
"Title","51.00150763193481, -2.5659284999999272", "link", "text"
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(55.153766, 11.909180),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
for (var x = 0; x < temp.length; x++) {
if(temp[x][1]){
var map_items = temp[x];
var myLatlng = new google.maps.LatLng(map_items[1]);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">'+map_items[0]+'<br /><p>'+map_items[3]+'</p></div>');
infowindow.open(map, marker);
});
}
}
}
google.maps.LatLng() takes two parameters, not one, so:
var latlon = map_items[1].split(',');
var myLatlng = new google.maps.LatLng(parseFloat(latlon[0]), parseFloat(latlon[1]));
though in fact, it would be better to use objects rather than an array in which each item contains different data types, for example:
marker_data[0] = {
"lat": 55.153766,
"lon": 11.909180,
"title": "My Title",
"link": "http://stackoverflow.com"
}
//etc...
and then you'd access it like this:
var myLatlng = new google.maps.LatLng(marker_data[0].lat, marker_data[0].lon);
Assuming map_items[1] is string
if (temp[x][1]) {
var map_items = temp[x];
var latlng = map_items[1].split(",");
var myLatlng = new google.maps.LatLng(parseFloat(latlng[0]), parseFloat(latlng[1]));
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">' + map_items[0] + '<br /><p>' + map_items[3] + '</p></div>');
infowindow.open(map, marker);
});
}
I think only last map_items would be available when you click on any marker. Creating a different context may solve your problem.
function initialize() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: new google.maps.LatLng(55.153766, 11.909180),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
function AttachEventToMarker(marker, map_items){
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<div class="google_marker">'+map_items[0]+'<br /><p>'+map_items[3]+'</p></div>');
infowindow.open(map, marker);
});
}
for (var x = 0; x < temp.length; x++) {
if(temp[x][1]){
var map_items = temp[x];
var myLatlng = new google.maps.LatLng(map_items[1]);
var marker = new google.maps.Marker({
map: map,
position: myLatlng,
title: map_items[0]
});
AttachEventToMarker(marker, map_items);
}
}
}

Categories

Resources