infowindow.setContent all the same thing...dealing with closures/Google Maps api - javascript

I've been wrestling with this infowindow.setContent(address); for hours. Based on what I've read on here I know it has to do something with closures but I can't get it to work. Both of my info windows are the same right now.
Here's the test site right now, sorry for the poor appearance :)
http://testsite.edwardgranger.com/2013/12/05/hello-world/
PHP & js code:
<script type="text/javascript">
var o = <?php echo json_encode($m_userArray); ?>
</script>
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<div id="map" style="width: 500px; height: 400px;"></div>
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(-33.92, 151.25),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker;
var i;
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
for(var i = 3; i <= 4; i++) {
var address = window.o[i].address;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(address);
infowindow.open(map, marker);
}
})(marker, i));
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
</script>
I've tried a few different concepts but honestly I just found out about closures tonight and I understand them on a higher level but trying to navigate my code is a chore, a second set of eyes would be great right now.

Related

Javascript Google Maps Api, multiple markers with links, only geoceder

I've got problems to put links on multiple markers, I can show my markers on the map, but when a I try tu put link on them, I have always the same link on all markers, the last. Here I provide a sample code:
<div id="map" style="height: 400px; width:100%;"></div>
<script>
var markers = [{"name":"Vasto","url":"http://www.google.com"},{"name":"Chieti","url":"http://www.wikipedia.com"}];
var geocoder;
var map;
var LatLng;
var url;
console.log(markers);
function initMap() {
LatLng = {lat: 42.2872297, lng: 13.3403448};
map = new google.maps.Map(document.getElementById('map'), {zoom: 8, center: LatLng});
geocoder = new google.maps.Geocoder();
setMarkers();
}
function setMarkers() {
var marker, i, url;
for( i = 0; i < markers.length; i++ ) {
url = markers[i].url;
geocoder.geocode({'address': markers[i].name}, function(results, status) {
if (status === 'OK') {
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=MYKEY&callback=initMap" async defer></script>
Any solutions?
Thanks in advance
Due to asynchronous code, you need to change your code a bit
function setMarkers() {
markers.forEach(function(item) {
var url = item.url;
geocoder.geocode({'address': item.name}, function(results, status) {
if (status === 'OK') {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: results[0].address_components[0].long_name,
});
google.maps.event.addListener(marker, "click", function() {
window.location.href = url;
});
} else {
/*console.log('Geocode was not successful for the following reason: ' + status);*/
}});
}
}

How to display certain names in google maps infowindow marker

I'm kind of stuck and was wondering if someone could help, here is a snippet of my code:
function test(person,address)
{
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 10,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode( { 'address': address[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker) {
//cant add information here dont know why...
return function() {
infowindow.setContent(person[0].cName + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker));
}
});
}//for
}//function
I'm passing an array of addresses and names. I've been trying to get each marker to display the person's name and address upon clicking on the infowindow of the marker on the map. This is where I'm having issues, I solved the address issue by just using the results[0].formatted_address but am unsure on how to display the specific user to that marker. Any tips would be appreciated.
You need function closure on the name as well as the marker in the click listener for the marker. As the name of the person needs to be available in the callback for the geocoder as well, you need function closure on the geocoder callback function as well.
Related questions
Google Maps V3 - I cannot reconcile closure
JS Geocoder cannot assign Global Variable for Google Maps Variable
proof of concept fiddle
code snippet:
function test(person, address) {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(43.761539, -79.411079),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow()
var marker, i;
var clatlng, clat, clng;
for (i = 0; i < address.length; i++) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address[i]
}, (function(name) {
return function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
clat = results[0].geometry.location.lat();
clng = results[0].geometry.location.lng();
clatlng = new google.maps.LatLng(clat, clng);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
google.maps.event.addListener(marker, 'click', (function(marker, name) {
//cant add information here dont know why...
return function() {
infowindow.setContent(name + "<br>" + results[0].formatted_address);
infowindow.open(map, marker);
}
})(marker, name));
}
}
})(person[i]));
} //for
} //function
function initialize() {
test(["fred", "george", "frank"], ["New York, NY", "Newark, NJ", "Toronto, CA"]);
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>

trouble getting my mouseover on markers to work

I have created my code below with the mouseover affect at the end, but it does not work. Have I put it in the wrong place? I just can't seem to get it to work. Eventually I would like to get a certain type of info displayed on them but each step at a time, trying to get the basic to work first.
<!DOCTYPE html>
<html>
<head>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message)
{
if (typeof console != 'undefined')
{
console.log(message);
}
}
up206b.initialize = function()
{
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function()
{
var addresses = [ $('#address').val(), $('#address2').val()];
addresses.forEach(function(address){
if(address){
geocoder.geocode( { 'address': address}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
}
else
{
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
</script>
</head>
<body onload="up206b.initialize()">
<div style="top: 0; right: 0; width:380px; height: 500px; float:right;padding-left:10px; padding-right:10px;">
<h1 align="center">Map Search</h1>
<div style="border:1px solid #ccc; background:#e5e5e5; padding:10px;" >
<form >
<br>
Location 1 <input type="text" id="address">
<br>
<br>
Location 2
<input type="text" id="address2">
<br>
<br>
<input type="button" value="Submit" onClick="up206b.geocode()">
</form>
</div>
</div>
<div id="map_canvas" style="height: 500px; width: 500px; float:right"></div>
You need to:
define contentString
associate the marker with the infowindow content. One way of doing that is with anonymous function closure as in this related question Google Maps JS API v3 - Simple Multiple Marker Example, or with an explicit createMarker function as in my example below.
Note: This approach will only work for approximately 10 addresses, after which it will run into the Geocoder rate limits.
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
}
proof of concept fiddle
code snippet:
var markers = [];
function createMarker(latlng, html, map) {
var infowindow = new google.maps.InfoWindow({
content: html
});
var marker = new google.maps.Marker({
map: map,
position: latlng
});
marker.addListener('mouseover', function() {
infowindow.open(map, this);
});
marker.addListener('mouseout', function() {
infowindow.close();
});
markers.push(marker);
}
//declare namespace
var up206b = {};
//declare map
var map;
function trace(message) {
if (typeof console != 'undefined') {
console.log(message);
}
}
up206b.initialize = function() {
var latlng = new google.maps.LatLng(52.136436, -0.460739);
var myOptions = {
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
up206b.geocode();
}
var geocoder = new google.maps.Geocoder();
up206b.geocode = function() {
for (var i = 0; i < markers.length; i++) {
markers[i].setMap(null);
}
markers = [];
var bounds = new google.maps.LatLngBounds();
var addresses = [$('#address').val(), $('#address2').val()];
addresses.forEach(function(address) {
if (address) {
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
createMarker(results[0].geometry.location, address, map);
bounds.extend(results[0].geometry.location);
map.fitBounds(bounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
}
google.maps.event.addDomListener(window, "load", up206b.initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="address" value="New York, NY" />
<input id="address2" value="Newark, NJ" />
<input type="button" value="Submit" onClick="up206b.geocode()">
<div id="map_canvas"></div>

Google Maps API infowindows all have the same content

I have the old infowindows in a loop problem where the content for the last loop is showing in all infowindows. Yes I know there are several questions about this already on Stack Overflow but none of them seem to work for me.
This is my JavaScript:
var map;
var geocoder;
$(function () {
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
var marker, i;
$('#map-canvas').height($('#map-canvas').width() / 2);
var mapOptions = {
zoom: startZoom,
center: new google.maps.LatLng(startLat, startLng)
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if ( ! isAddress && $('#country').val() > 0) {
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': $('#country').find('option:selected').text()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
map.fitBounds(results[0].geometry.viewport);
}
});
}
for (i = 0; i < distributors.length; i++) {
var $distributor = distributors[i];
var marker = new google.maps.Marker({
position: new google.maps.LatLng($distributor.latitude, $distributor.longitude),
map: map
});
var infowindow = new google.maps.InfoWindow();
var html = '<div class="container-fluid" style="width: 300px">\
<h1 class="row-fluid">\
'+($distributor.logo ? '<div class="span3"><img src="'+$distributor.logo+'" style="width: 100%"></div>' : '')+'\
<span class="span9">'+$distributor.name+'</span>\
</h1>\
<div class="row-fluid">\
<div class="span6">'+$distributor.address+'<br>'+$distributor.postcode+'</div>\
<div class="span6">'+($distributor.url ? ''+$distributor.url+'' : '')+'<br>'+$distributor.contactNumber+'</div>\
</div>\
</div>';
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(html);
infowindow.open(map, marker);
}
})(marker, i));
}
})
So far I've tried this answer, but the variables mentioned don't match what I have and I couldn't make them match up, it just didn't work.
I've also tried this answer, but instead of getting different content it removed all but one of my markers.
What am I doing wrong? Can someone please help me sort this out?
Try this after creating infoWindow and html objects:
marker.html = html;
Then build your event listener like this:
google.maps.event.addListener(marker, 'click', function () {
infoWindow.setContent(this.html);
infoWindow.open(map, this);
});

Marker population from address

Following is my code which i am using to populate marker from the array address but its not showing any marker nor map to the respective div, Kindly let me know what i did wrong and how can i resolve this issue.
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
$(document).ready(function(){
var myOptions = {
center: new google.maps.LatLng(54, -2),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var addressArray = new Array("41 Green Ln, Handsworth, Birmingham, West Midlands B21 0DE, UK","BT27 4SB","Norwich");
var geocoder = new google.maps.Geocoder();
var markerBounds = new google.maps.LatLngBounds();
for (var i = 0; i < addressArray.length; i++) {
geocoder.geocode( { 'address': addressArray[i]}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
markerBounds.extend(results[0].geometry.location);
map.fitBounds(markerBounds);
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
});
</script>
<div id="map_canvas"></div>
In order for the map to display, you'll need to give #map_canvas an absolute width/height using CSS.
Example fiddle: http://jsfiddle.net/sCvJk/

Categories

Resources