How to Display Multiple Google Maps per page with API V3 - javascript

I have the following script. And I want to make both maps appear on the page, but no matter what I try I can only get the first map initialize() to display... the second one doesn't. Any suggestions? (also, I can't add it in the code, but the first map is being displayed in <div id="map_canvas"></div><div id="route"></div>
Thanks!
<script type="text/javascript">
// Create a directions object and register a map and DIV to hold the
// resulting computed directions
var map;
var directionsPanel;
var directions;
function initialize() {
map = new GMap(document.getElementById("map_canvas"));
map.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
directionsPanel = document.getElementById("route");
directions = new GDirections(map, directionsPanel);
directions.load("from: Armonk Fire Department, Armonk NY to: <?php echo $LastCallGoogleAddress;?> ");
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
}
</script>
<div id="map_canvas2" style="width:200px; height:200px;"></div>
<div id="route2"></div>
<script type="text/javascript">
// Create a directions object and register a map and DIV to hold the
// resulting computed directions
var map2;
var directionsPanel2;
var directions2;
function initialize2() {
map2 = new GMap(document.getElementById("map_canvas2"));
map2.setCenter(new GLatLng(41.1255275,-73.6964801), 15);
directionsPanel2 = document.getElementById("route2");
directions2 = new GDirections(map2, directionsPanel2);
directions2.load("from: ADDRESS1 to: ADDRESS2 ");
map2.addControl(new GSmallMapControl());
map2.addControl(new GMapTypeControl());
}
</script>
<script type="text/javascript">
function loadmaps(){
initialize();
initialize2();
}
</script>

Here is how I have been able to generate multiple maps on the same page using Google Map API V3. Kindly note that this is an off the cuff code that addresses the issue above.
The HTML bit
<div id="map_canvas" style="width:700px; height:500px; margin-left:80px;"></div>
<div id="map_canvas2" style="width:700px; height:500px; margin-left:80px;"></div>
Javascript for map initialization
<script type="text/javascript">
var map, map2;
function initialize(condition) {
// create the maps
var myOptions = {
zoom: 14,
center: new google.maps.LatLng(0.0, 0.0),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
map2 = new google.maps.Map(document.getElementById("map_canvas2"), myOptions);
}
</script>

I have just finished adding Google Maps to my company's CMS offering. My code allows for more than one map in a page.
Notes:
I use jQuery
I put the address in the content and then parse it out to dynamically generate the map
I include a Marker and an InfoWindow in my map
HTML:
<div class="block maps first">
<div class="content">
<div class="map_canvas">
<div class="infotext">
<div class="location">Middle East Bakery & Grocery</div>
<div class="address">327 5th St</div>
<div class="city">West Palm Beach</div>
<div class="state">FL</div>
<div class="zip">33401-3995</div>
<div class="country">USA</div>
<div class="phone">(561) 659-4050</div>
<div class="zoom">14</div>
</div>
</div>
</div>
</div>
<div class="block maps last">
<div class="content">
<div class="map_canvas">
<div class="infotext">
<div class="location">Global Design, Inc</div>
<div class="address">3434 SW Ash Pl</div>
<div class="city">Palm City</div>
<div class="state">FL</div>
<div class="zip">34990</div>
<div class="country">USA</div>
<div class="phone"></div>
<div class="zoom">17</div>
</div>
</div>
</div>
</div>
Code:
$(document).ready(function() {
$maps = $('.block.maps .content .map_canvas');
$maps.each(function(index, Element) {
$infotext = $(Element).children('.infotext');
var myOptions = {
'zoom': parseInt($infotext.children('.zoom').text()),
'mapTypeId': google.maps.MapTypeId.ROADMAP
};
var map;
var geocoder;
var marker;
var infowindow;
var address = $infotext.children('.address').text() + ', '
+ $infotext.children('.city').text() + ', '
+ $infotext.children('.state').text() + ' '
+ $infotext.children('.zip').text() + ', '
+ $infotext.children('.country').text()
;
var content = '<strong>' + $infotext.children('.location').text() + '</strong><br />'
+ $infotext.children('.address').text() + '<br />'
+ $infotext.children('.city').text() + ', '
+ $infotext.children('.state').text() + ' '
+ $infotext.children('.zip').text()
;
if (0 < $infotext.children('.phone').text().length) {
content += '<br />' + $infotext.children('.phone').text();
}
geocoder = new google.maps.Geocoder();
geocoder.geocode({'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
myOptions.center = results[0].geometry.location;
map = new google.maps.Map(Element, myOptions);
marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
title: $infotext.children('.location').text()
});
infowindow = new google.maps.InfoWindow({'content': content});
google.maps.event.addListener(map, 'tilesloaded', function(event) {
infowindow.open(map, marker);
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, marker);
});
} else {
alert('The address could not be found for the following reason: ' + status);
}
});
});
});

OP wanted two specific maps, but if you'd like to have a dynamic number of maps on one page (for instance a list of retailer locations) you need to go another route. The standard implementation of Google maps API defines the map as a global variable, this won't work with a dynamic number of maps. Here's my code to solve this without global variables:
function mapAddress(mapElement, address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': address }, function (results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var mapOptions = {
zoom: 14,
center: results[0].geometry.location,
disableDefaultUI: true
};
var map = new google.maps.Map(document.getElementById(mapElement), mapOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
Just pass the ID and address of each map to the function to plot the map and mark the address.

I needed to load dynamic number of google maps, with dynamic locations. So I ended up with something like this. Hope it helps. I add LatLng as data-attribute on map div.
So, just create divs with class "maps". Every map canvas can than have a various IDs and LatLng like this. Of course you can set up various data attributes for zoom and so...
Maybe the code might be cleaner, but it works for me pretty well.
<div id="map123" class="maps" data-gps="46.1461154,17.1580882"></div>
<div id="map456" class="maps" data-gps="45.1461154,13.1080882"></div>
<script>
var map;
function initialize() {
// Get all map canvas with ".maps" and store them to a variable.
var maps = document.getElementsByClassName("maps");
var ids, gps, mapId = '';
// Loop: Explore all elements with ".maps" and create a new Google Map object for them
for(var i=0; i<maps.length; i++) {
// Get ID of single div
mapId = document.getElementById(maps[i].id);
// Get LatLng stored in data attribute.
// !!! Make sure there is no space in data-attribute !!!
// !!! and the values are separated with comma !!!
gps = mapId.getAttribute('data-gps');
// Convert LatLng to an array
gps = gps.split(",");
// Create new Google Map object for single canvas
map = new google.maps.Map(mapId, {
zoom: 15,
// Use our LatLng array bellow
center: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
mapTypeId: 'roadmap',
mapTypeControl: true,
zoomControlOptions: {
position: google.maps.ControlPosition.RIGHT_TOP
}
});
// Create new Google Marker object for new map
var marker = new google.maps.Marker({
// Use our LatLng array bellow
position: new google.maps.LatLng(parseFloat(gps[0]), parseFloat(gps[1])),
map: map
});
}
}
</script>

Here's another example if you have the long and lat, in my case using Umbraco Google Map Datatype package and outputting a list of divs with class "map" eg.
<div class="map" id="UK">52.21454000000001,0.14044490000003407,13</div>
my JavaScript using Google Maps API v3 based on Cultiv Razor examples
$('.map').each(function (index, Element) {
var coords = $(Element).text().split(",");
if (coords.length != 3) {
$(this).display = "none";
return;
}
var latlng = new google.maps.LatLng(parseFloat(coords[0]), parseFloat(coords[1]));
var myOptions = {
zoom: parseFloat(coords[2]),
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
mapTypeControl: true,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.SMALL
}
};
var map = new google.maps.Map(Element, myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
});

Taken from These examples - guide , implementation .
set your <div>'s with the appropriate id
include the Google Map options with foundation calling.
include foundation and rem js lib .
Example -
index.html -
<div class="row">
<div class="large-6 medium-6 ">
<div id="map_canvas" class="google-maps">
</div>
</div>
<br>
<div class="large-6 medium-6 ">
<div id="map_canvas_2" class="google-maps"></div>
</div>
</div>
<script src="/js/foundation.js"></script>
<script src="/js/google_maps_options.js"></script>
<script src="/js/rem.js"></script>
<script>
jQuery(function(){
setTimeout(initializeGoogleMap,700);
});
</script>
google_maps_options.js -
function initializeGoogleMap()
{
$(document).foundation();
var latlng = new google.maps.LatLng(28.561287,-81.444465);
var latlng2 = new google.maps.LatLng(28.507561,-81.482359);
var myOptions =
{
zoom: 13,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var myOptions2 =
{
zoom: 13,
center: latlng2,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var map2 = new google.maps.Map(document.getElementById("map_canvas_2"), myOptions2);
var myMarker = new google.maps.Marker(
{
position: latlng,
map: map,
title:"Barnett Park"
});
var myMarker2 = new google.maps.Marker(
{
position: latlng2,
map: map2,
title:"Bill Fredrick Park at Turkey Lake"
});
}

You haven't defined a div with id="map_canvas", you only have id="map_canvas2" and id="route2". The div ids need to match the argument in the GMap() constructor.

You could try nex approach
css
.map {
height: 300px;
width: 100%;
}
HTML
#foreach(var map in maps)
{
<div id="map-#map.Id" lat="#map.Latitude" lng="#map.Longitude" class="map">
</div>
}
JavaScript
<script>
var maps = [];
var markers = [];
function initMap() {
var $maps = $('.map');
$.each($maps, function (i, value) {
var uluru = { lat: parseFloat($(value).attr('lat')), lng: parseFloat($(value).attr('lng')) };
var mapDivId = $(value).attr('id');
maps[mapDivId] = new google.maps.Map(document.getElementById(mapDivId), {
zoom: 17,
center: uluru
});
markers[mapDivId] = new google.maps.Marker({
position: uluru,
map: maps[mapDivId]
});
})
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?language=ru-Ru&key=YOUR_KEY&callback=initMap">
</script>

I had one especific issue, i had a Single Page App and needed to show different maps, in diferent divs, one each time. I solved it in not a very beautiful way but a functionally way. Instead of hide the DOM elements with display property i used the visibility property to do it. With this approach Google Maps API had no trouble about know the dimensions of the divs where i had instantiated the maps.

var maps_qty;
for (var i = 1; i <= maps_qty; i++)
{
$(".append_container").append('<div class="col-lg-10 grid_container_'+ (i) +'" >' + '<div id="googleMap'+ i +'" style="height:300px;"></div>'+'</div>');
map = document.getElementById('googleMap' + i);
initialize(map,i);
}
// Intialize Google Map with Polyline Feature in it.
function initialize(map,i)
{
map_index = i-1;
path_lat_long = [];
var mapOptions = {
zoom: 2,
center: new google.maps.LatLng(51.508742,-0.120850)
};
var polyOptions = {
strokeColor: '#000000',
strokeOpacity: 1.0,
strokeWeight: 3
};
//Push element(google map) in an array of google maps
map_array.push(new google.maps.Map(map, mapOptions));
//For Mapping polylines to MUltiple Google Maps
polyline_array.push(new google.maps.Polyline(polyOptions));
polyline_array[map_index].setMap(map_array[map_index]);
}
// For Resizing Maps Multiple Maps.
google.maps.event.addListener(map, "idle", function()
{
google.maps.event.trigger(map, 'resize');
});
map.setZoom( map.getZoom() - 1 );
map.setZoom( map.getZoom() + 1 );

Take a Look at this Bundle for Laravel that I Made Recently !
https://github.com/Maghrooni/googlemap
it helps you to create one or multiple maps in your page !
you can find the class on
src/googlemap.php
Pls Read the readme file first and don't forget to pass different ID if you want to have multiple Maps in one page

Related

Adding Javascript Functions to Load Google Maps C# WPF

I am trying to integrate Google Maps into a WebBrowserControl in my C# WPF program. The map loads in the control and centers on the correct latitude and longitude, however I am having a couple of errors. First of all, the map loads and after a couple of seconds I get an error box appear;
Secondly, when I am trying to add a marker on the location of the latitude and longitude, I get an error even before the map loads at all. Here is my code so far;
mapWebBrowser.NavigateToString(#"<html xmlns=""http://www.w3.org/1999/xhtml"" xmlns:v=""urn:schemas-microsoft-com:vml"">
<head>
<meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge""/>
<meta name = ""viewport"" content = ""initial-scale=1.0, user-scalable=no""/>
<script type = ""text/javascript""
src = ""http://maps.google.com.mx/maps/api/js?sensor=true&language=""es"" ></script>
<script src = 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js'>
</script><script type = ""text/javascript"">
function initialize() {
var latlng = new google.maps.LatLng(" + latitude + ", " + longitude + #");
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(""map_canvas""), myOptions);
}
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
</script>
</head>
<body onload = ""initialize()"" >
<div id=""map_canvas"" style=""width:100%; height:100%""></div>
</body>
</html>");
This is the function I am attempting to use to add a marker onto the map;
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
Which I call in C#;
mapWebBrowser.InvokeScript("addMarker", new object[] { latitude, longitude } );
Unfortunately as I stated before both methods are causing issues.
I believe there was a change in Google's APIs back in June and they now require authentication for google maps. I don't see your API key being supplied anywhere. I would suggest you try your HTML/javascript in the browser or where you can sniff the requests and the responses and see what's going on.
If you still can't solve your problem. You may use Script Errors Suppressed too. Then this window will disappear.
webBrowser1.ScriptErrorsSuppressed = true;

My google places kml url javascript

i have a problem with my places from google maps, i already have a functionality map with a file kml in my https server, but i don't want to download and upload the map every time I make changes, not work for me only embed I need manipulated with API, so this is my code:
var map;
var src = 'MY_SERVER/points_vl.kmz';
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(20.63736, -105.22883),
zoom: 2,
});
loadKmlLayer(src, map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = 'http://www.nearby.org.uk/google/circle.kml.php?radius=5miles&lat='+position.coords.latitude+'&long='+position.coords.longitude;
loadKmlLayer(circle, map);
map.setCenter(pos);
setTimeout(function(){
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
infowindow.setPosition(pos);
}, 2000);
});
}
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
This work fine, but have a way for direct the kml from my url of google maps places?
Using an existant Google 'My Places' map with Maps API v3 styling this thread have some idea, but not work, if you get a idea how make it will make it wonderful
Go to your "MyMap" map. Click on the three dots next to the name of the map, click on "Export to KML":
Choose the "Keep data up to date with network link KML (only usable online):
Rename the .kmz file to .zip, then open it and open the doc.kml file it contains. That file will have the direct link to the KML data specifying your "MyMap".
Use that link in a google.maps.KmlLayer
proof of concept fiddle
original MyMap
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: 41.876,
lng: -87.624
}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'https://www.google.com/maps/d/kml?mid=1-mpfnFjp1e5JJ1YkSBjE6ZX_d9w',
map: map
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<!-- add your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

How to show Google Map marker dynamically in a Laravel view page?

I found some JavaScript code on the internet. It's helping me to store the latitude and longitude of a place, from the Google Map by moving the marker on my database table.
Database column names are la|lo. Now I want to show the location on a view page. The map should have these properties frameborder="0", scrolling="no", marginheight="0", marginwidth="0", width="250", height="272".
I'm a novice and I have poor knowledge on JavaScript. I'm providing the js code of registering the latitude and longitude.
<script
src="http://maps.googleapis.com/maps/api/js">
</script>
<script>
function initialize() {
var latitude = 23.786758526804636;
var longitude = 90.39979934692383;
var zoom = 11;
var LatLng = new google.maps.LatLng(latitude, longitude);
var mapProp = {
center: LatLng,
zoom:12,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("googleMap"), mapProp);
var marker = new google.maps.Marker({
position: LatLng,
map: map,
title: 'Drag Me!',
draggable: true
});
google.maps.event.addListener(marker, 'dragend', function(event) {
document.getElementById('la').value = event.latLng.lat();
document.getElementById('lo').value = event.latLng.lng();
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="googleMap" style="width:auto;height:400px;"></div>
<input type="hidden" id="la" name="la">
<input type="hidden" id="lo" name="lo">
Since you indicated the lat/long are in the database, you can just retrieve it and set it on a array list in js. After that, you'll just need to iterate the list to add markers based on it.
The code here is from the official documentation provided.
function initMap() {
var myLatLng = {lat: -25.363, lng: 131.044};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: myLatLng
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Hello World!'
});
}
For styling, you can check out the Styled Maps page in the official documentation. It should be sufficient enough with what you want to set in your post.

Doing a Google Maps reverse geocode and displaying the result as part as HTML content inside an infowindow

I have put together this script (note: I'm using jQuery 1.11.2) that gets lat long coordinates from a PHP operation (used for something else) and displays a map with a customized marker and infowindow that includes HTML for formatting the information that is displayed.
<script src="https://maps.googleapis.com/maps/api/js?v=3.20&sensor=false"></script>
<script type="text/javascript">
var maplat = 41.36058;
var maplong = 2.19234;
function initialize() {
// Create a Google coordinate object for where to center the map
var latlng = new google.maps.LatLng( maplat, maplong ); // Coordinates
var mapOptions = {
center: latlng,
zoom: 3,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false,
streetViewControl: false,
zoomControl: false,
mapTypeControl: false,
disableDoubleClickZoom: true
};
map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
// CREATE AN INFOWINDOW FOR THE MARKER
var content = 'This will show up inside the infowindow and it is here where I would like to show the converted lat/long coordinates into the actual, human-readable City/State/Country'
; // HTML text to display in the InfoWindow
var infowindow = new google.maps.InfoWindow({
content: content,maxWidth: 250
});
var marker = new google.maps.Marker( {
position: latlng,
map: map,
title: "A SHORT BUT BORING TITLE",
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
infowindow.open(map,marker);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
What I'm trying to achieve is to do a reverse geocode on the coordinates stored in the latlng variable and get back the results of that in a "City, State, Country" format and insert that into the HTML for the informarker stored in the "content" variable.
Have tried multiple approaches without success. Please note that I've deliberately left out the reverse geocoding script I tried to use for clarity purposes.
Edit: I've adjusted the script presented here to comply with the rules about it being clear, readable and that it actually should work. I also include a link to a CodePen so that you can see it in action: Script on CodePen
Regarding including the script for reverse geocoding, what I did was a disaster, only breaking the page and producing "undefined value" errors. I'd like to learn the correct way of doing this by example, and that's where the wonderful StackOverflow community comes in. Thanks again for your interest in helping me out.
Use a node instead of a string as content , then you may place the geocoding-result inside the content, no matter if the infoWindow is already visible or not or when the result is available(it doesn't even matter if the InfoWindow has already been initialized, a node is always "live").
Simple Demo:
function initialize() {
var geocoder = new google.maps.Geocoder(),
latlng = new google.maps.LatLng(52.5498783, 13.42520);
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 18,
center: latlng
}),
marker = new google.maps.Marker({
map: map,
position: latlng
}),
content = document.createElement('div'),
infoWin = new google.maps.InfoWindow({
content: content
});
content.innerHTML = '<address>the address should appear here</address>';
google.maps.event.addListener(marker, 'click', function() {
infoWin.open(map, this);
});
geocoder.geocode({
location: latlng
}, function(r, s) {
if (s === google.maps.GeocoderStatus.OK) {
content.getElementsByTagName('address')[0].textContent = r[0].formatted_address;
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<div id="map-canvas"></div>
Here's how I would do it:
function reverseGeocoder(lat, lng, callback) {
var geocoder = new google.maps.Geocoder();
var point = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
geocoder.geocode({"latLng" : point }, function(data, status) {
if (status == google.maps.GeocoderStatus.OK && data[0]) {
callback(null, data[0].formatted_address);
} else {
console.log("Error: " + status);
callback(status, null);
}
});
};
And basically you would call the function like:
reverseGeocoder(lat, lng, function(err, result){
// Do whatever has to be done with result!
// EDIT: For example you can pass the result to your initialize() function like so:
initialize(result); // And then inside your initialize function process the result!
});

Google Maps v3 Listener (click) - Change URL

I have a Google Maps map with a markercluster, and various points. Generating the points like below with the event listener, it goes off for every single point on page load.
function mappyfuntime() {
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
<?php echo prepare_javascript(); ?>
var markers = [];
var marker = [];
linkto = new Array();
for(g=0; g<LocationsArray.length; g++) {
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
marker[g] = new google.maps.Marker({'position': latlng});
markers.push(marker[g]);
google.maps.event.addListener(marker[g], 'click', click_handler(PermalinksArray[g]));
}
var markerCluster = new MarkerClusterer(map, markers);
}
mappyfuntime();
function click_handler(link) {
alert(link);
}
However, if I change the google.maps.event.addListener to the following, the alert comes back undefined.
google.maps.event.addListener(marker[g], 'click', function() {
alert(PermalinksArray[g]);
});
And if I pass PermalinksArray[g] to the function, the same thing happens. Is there any way to get a piece of information from an array (which is globally defined) when its corresponding point is clicked on the map?
I guess the Permalinks Array comes from the php insert? Well then its not in global scope. Try puttung that php-insert at the top of your javascript script.
// set globals
var map;
var markers = [];
var PermalinksArray = ['...'];
var LocationsArray = ['...'];
function mappyfuntime() {
// init map
var mapOptions = {
center: new google.maps.LatLng(51.481581,-3.17909),
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("bigmap"), mapOptions);
// create markers
for(g=0; g<LocationsArray.length; g++) {
// create new Position
var latlng = new google.maps.LatLng(LocationsArray[g][0], LocationsArray[g][1]);
// create new marker with position
var marker = new google.maps.Marker({'position': latlng});
// add event to marker
google.maps.event.addListener(marker, 'click', function() {
click_handler(marker, PermalinksArray[g]);
});
// push marker into markers array
markers.push(marker);
}
var markerCluster = new MarkerClusterer(map, markers);
}
function click_handler(marker, link) {
alert(link);
}
mappyfuntime();
I have created a Google Map with 2 markers and when a marker is clicked then the area's name appears in the info window. The information in the markers is loaded through a global defined array named cityList. You can find my code below.
<!doctype html>
<html lang="en">
<head>
<title>jQuery mobile with Google maps - Google maps jQuery plugin</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?v=3&sensor=false&language=en"> </script>
<script type="text/javascript">
var cityList = [
['Chicago', 41.850033, -87.6500523, 1],
['Illinois', 40.797177,-89.406738, 2]
],
demoCenter = new google.maps.LatLng(41,-87),
map;
function initialize()
{
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 7,
center: demoCenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function addMarkers()
{
var marker, i;
var infowindow = new google.maps.InfoWindow();
for (i = 0; i < cityList.length; i++)
{
marker = new google.maps.Marker({
position: new google.maps.LatLng(cityList[i][1], cityList[i][2]),
map: map,
title: cityList[i][0]
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(cityList[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
$(document).on("pageinit", "#basic-map", function() {
initialize();
});
$(document).on('click', '.add-markers', function(e) {
e.preventDefault();
addMarkers();
});
</script>
</head>
<body>
<div id="basic-map" data-role="page">
<div data-role="header">
<h1><a data-ajax="false" href="/">jQuery mobile with Google maps v3</a> examples</h1>
<a data-rel="back">Back</a>
</div>
<div data-role="content">
<div class="ui-bar-c ui-corner-all ui-shadow" style="padding:1em;">
<div id="map_canvas" style="height:350px;"></div>
</div>
Add Some More Markers
</div>
</div>
</body>
</html>
I hope this helps.

Categories

Resources