I'm working on a web app that includes google map and a bunch of markers.
This morning I had working map+markers from db (but I used only one table with data).
ss this morning:
Now I'm trying to put marker custom icons and info windows to get something like this (this was made without laravel, only php).
This is my code:
#extends('layouts.app')
#section('content')
<script src="http://maps.google.com/maps/api/js?sensor=false"
type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function load() {
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
var infoWindow = new google.maps.InfoWindow;
#foreach($markers as $marker)
var sadrzaj = {{$marker->nazivMarkera}};
var adresa = {{$marker->adresa}};
var grad = {{$marker->nazivGrada}};
var postanskibroj = {{$marker->postanski_broj}};
var zupanija = {{$marker->nazivZupanije}};
var html = "<b>" + sadrzaj + "</b> <br/>" + adresa +",<br/>"+postanskibroj+" "+grad+",<br/>"+zupanija;
var lat = {{$marker->lat}};
var lng = {{$marker->lng}};
var image = {{$marker->slika}};
var markerLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var mark = new google.maps.Marker({
map: map,
position: markerLatlng,
icon: image
});
bindInfoWindow(mark, map, infoWindow, html);
#endforeach
}
function bindInfoWindow(mark, map, infoWindow, html){
google.maps.event.addListener(marker, 'click', function(){
infoWindow.setContent(html);
infowWindow.open(map, mark);
});
}
function doNothing(){}
//]]>
</script>
<div class="container">
<div class="row">
<div class="col-md-10 col-md-offset-1">
<div class="panel panel-default">
<div class="panel-heading">Dobro došli!</div>
<div class="panel-body">
<!-- Moj kod -->
<div id="map"></div>
<!-- DO TU -->
</div>
</div>
</div>
</div>
</div>
#endsection
When I inspect the page I can see that my array with data is filled and I have all the data from db.
Can someone help me and explain to me where is the problem? Why when I remove functions for markers, and set only map init, I get map view with no problem, and now I don't even get the map.
Now:
It looks like load() is not getting called anywhere.
Also I noticed in your screen shots, the variables which have been echoed in by laravel don't have quotes around them.
I would leave laravel(blade) out of the javascript. Currently, your foreach loop will dump heaps of javascript code which will be overriding and re-declaring variables. This is generally messy, and considered bad practice.
I would also make map a global variable, incase you want to manipulate it later.
Try this:
var map;
var markers = {!! json_encode($markers) !!}; //this should dump a javascript array object which does not need any extra interperting.
var marks = []; //just incase you want to be able to manipulate this later
function load() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
for(var i = 0; i < markers.length; i++){
marks[i] = addMarker(markers[i]);
}
}
function addMarker(marker){
var sadrzaj = marker.nazivMarkera};
var adresa = marker.adresa;
var grad = marker.nazivGrada;
var postanskibroj = marker.postanski_broj;
var zupanija = marker.nazivZupanije;
var html = "<b>" + sadrzaj + "</b> <br/>" + adresa +",<br/>"+postanskibroj+" "+grad+",<br/>"+zupanija;
var markerLatlng = new google.maps.LatLng(parseFloat(marker.lat),parseFloat(marker.lng));
var mark = new google.maps.Marker({
map: map,
position: markerLatlng,
icon: marker.slika
});
var infoWindow = new google.maps.InfoWindow;
google.maps.event.addListener(mark, 'click', function(){
infoWindow.setContent(html);
infoWindow.open(map, mark);
});
return mark;
}
function doNothing(){} //very appropriately named function. whats it for?
I also fixed up several small errors in the code, such as
info window was spelt wrong inside your bind function "infowWindow"
your infoWindow listener need to bind to mark not marker
you don't really need to individually extract out each variable from marker
Also, you need to call the load() function from somewhere. Maybe put onLoad="load()" on your body object or top level div. Or use the google DOM listener:
google.maps.event.addDomListener(window, 'load', load);
This will execute your load() function when the window is ready.
You have lo leave
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 45.327168, lng: 14.442902},
zoom: 13
});
out of the commented area, otherwise you're not initializing it.
Related
I have this google map which is working, I want to add a button on infowindow which somehow is not working. Though the function is defined but still throw error
http://jsfiddle.net/mpgxn53q/
<div id="apptMap"></div>
//the js code
<script src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
var locations = [["158845-001 - Adas Israel Congregation",38.9369545,-77.0575097,1],["163888-137 - Construction LLC",43.1765812,-84.6986701,2.0],["163888-155 - Construction LLC",43.1765812,-84.6986701,3.0],["167176-007 - GLDB MTM10 GLR016",42.4894512,-95.5449508,4.0],["167195-003 - 91622 DB A4",42.8275053,-84.5717997,5.0],["167195-002 - 91622 DB A4",42.8275053,-84.5717997,6.0],["167176-005 - GLDB MTM10 GLR016",42.0023,-93.6110955,7.0],["167176-004 - GLDB MTM10 GLR016",42.0023,-93.6110955,8.0]];
var map;
var markers = [];
function init(){
map = new google.maps.Map(document.getElementById('apptMap'), {
zoom: 10,
center: new google.maps.LatLng(42.0023,-93.6110955),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var num_markers = locations.length;
for (var i = 0; i < num_markers; i++) {
markers[i] = new google.maps.Marker({
position: {lat:locations[i][1], lng:locations[i][2]},
map: map,
html: locations[i][0],
id: i,
});
google.maps.event.addListener(markers[i], 'click', function(){
var infowindow = new google.maps.InfoWindow({
id: this.id,
content:this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>',
position:this.getPosition()
});
google.maps.event.addListenerOnce(infowindow, 'closeclick', function(){
markers[this.id].setVisible(true);
});
this.setVisible(false);
infowindow.open(map);
});
}
}
function mapsZoomMarker(wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
init();
There is a problem with scopes, and that's because of that how you wrote your script. I am not going to rewrite your script, but I will give you solution for your exact situation.
You need to define your function mapsZoomMarker in global scope (window object) like this:
window.mapsZoomMarker = function (wnMarker){
map.setCenter(markers[wnMarker].getPosition());
map.setZoom(15);
}
And there is also a mistake, in the function which is called when the marker is clicked. When you assign the html for the popup like this
content: this.html +'<button onclick="mapsZoomMarker('+i+')">Click me</button>'
the i variable is already set to 8, so instead of that just use this.id like this:
content: this.html +'<button onclick="mapsZoomMarker('+this.id+')">Click me</button>'
And this is the updated fiddle http://jsfiddle.net/rn27f05v/
I will propose a solution that I think is best for what you want. Instead call function inside var infowindow, you can only define a variable to put content your want.
You can change you var infowindow to:
var infowindow = new google.maps.InfoWindow({
id: this.id,
content: content, //here the variable that call your content
position:this.getPosition()
});
So... above your google.maps.event.addListener(markers[i], 'click', function(){... you can add:
var content = '<button onclick="mapsZoomMarker('+i+')">Click me</button>';
This way the click action will work.
Hope this tip help you.
Hey first time posting here. Trying to post multiple markers that I am pulling in from an API. I am a novice programmer, but I believe closures in the issue. I have tried many variations but I still can't get it to work. Can someone take a look?
$data = json_decode($json);
//var_dump($data);
foreach($data as $object):?>
<?php endforeach;
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCGLTlvxWSV6x4yH5XqqItlgHHIPt8GYp0" type="text/javascript"></script>
<script type="text/javascript">
var lat = '<?php echo $object->{'latitude'}?>';
var long = '<?php echo $object->{'longitude'}?>';
// check DOM Ready
$(document).ready(function() {
// execute
(function() {
// map options
var options = {
zoom: 5,
center: new google.maps.LatLng(39.909736, -98.522109), // centered US
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
// init map
var map = new google.maps.Map(document.getElementById('map_canvas'), options);
// set multiple marker
for (var i = 0; i < 1000; i++) {
// init markers
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,long),
map: map,
title: 'Check-In ' + i
});
// process multiple info windows
(function(marker, i) {
// add click event
google.maps.event.addListener(marker, 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: '<?php echo $object->{'username'}?>'
});
infowindow.open(map, marker);
});
})(marker, i);
};
})();
});
</script>
</head>
<body>
<div id="map_canvas" style="width: 800px; height:500px;"></div>
</body>
You're in for a world of hurt if you intersperse PHP loops with JavaScript loops like this. What you should do instead is generate a JSON array or JavaScript object for your markers from PHP, and then loop through your array in JavaScript.
For example, you could generate this JavaScript array from PHP:
var places = [
{ lat:10, lng:20, username:"Weez" },
{ lat:30, lng:40, username:"Mike" }
];
You can see where you could use your foreach loop to generate this, or use PHP's json_encode function.
Then your JavaScript code might look something like this:
$(document).ready(function() {
var options = {
zoom: 5,
center: new google.maps.LatLng( 39.909736, -98.522109 ),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: false
};
var map = new google.maps.Map(
document.getElementById('map_canvas'),
options
);
places.forEach( function( place, index ) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng( place.lat, place.lng ),
map: map,
title: 'Check-In ' + index
});
google.maps.event.addListener( marker, 'click', function() {
var infowindow = new google.maps.InfoWindow({
content: place.username
});
infowindow.open( map, marker );
});
});
});
I took out a couple of nested inline functions that aren't necessary. You are right that you need a closure (or some other mechanism) to capture the username for each of your markers to use in the click event handler, but the the callback function used with the .forEach() loop provides that closure for you. place, index, and marker are unique variables for each iteration of the loop, because they are arguments or local variables in the callback. So when you use place.username inside the click handler it has the value you expect.
I am trying to embed a weather widget from http://www.weather.com/services/oap/weather-widgets.html into an Info Window of a Google map, such that when I click on a marker, the weather widget is open in the Infowindow.
The code for embedding the weather widget is as follows (for San-Francisco, CA):
and it works fine when I put it into HTML:
<html>
<head>
</head>
<body>
<div style="width:270px;height:175px;border:1px solid blue;padding:10px">
<script type="text/javascript" src="http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget"></script>
</div>
</body>
</html>
However, when I try to use it in the following code that is supposed to show the widget in the InfoWindow on the Google map it does not work:
<html><head>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script type="text/javascript">
function initialize() {
var cpoint = new google.maps.LatLng(37.770728 ,-122.458199 );
var mapOptions = {
zoom: 4,
center: cpoint,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var infowindow = new google.maps.InfoWindow();
var info1 = '<div style="width:270px;height:175px;border:1px solid blue;padding:10px"><script type="text/javascript" src="http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget"></script></div>';
var point1 = new google.maps.LatLng(37.770728 ,-122.458199 );
var marker1 = new google.maps.Marker({
position: point1 ,
map: map,
title: "Click here for details"
});
google.maps.event.addListener(marker1 , "click", function() {
infowindow.setContent(info1 );
infowindow.open(map,marker1 );
});
}google.maps.event.addDomListener(window, "load", initialize);
</script>
</head><body>
<div id="map-canvas" style="width:750px; height:450px; border: 2px solid #3872ac;"></div>
</body></html>
All I do is I put that div into info1 Javascript variable. I am not sure whether I do anything wrong, or InfoWindow does not allow to do that.
I finally was able to figure this out using iframe tag. See my blog post Weather forecasting with SAS-generated Google maps.
First, I created weather mini-pages:
%macro create_widgets;
%let dsid = %sysfunc(open(places));
%let num = %sysfunc(attrn(&dsid,nlobs));
%let rc = %sysfunc(close(&dsid));
%do j=1 %to #
data _null_;
p = &j;
set places point=p;
file "&proj_path\widgets\accuweather_com_widget&j..html";
put
'<html><body>' /
'' /
'<div id="' dataid +(-1) '" class="aw-widget-current" data-locationkey="' lockey +(-1) '" data-unit="f" data-language="en-us" data-useip="false" data-uid="' dataid +(-1) '" data-editlocation="false"></div>' /
'<script type="text/javascript" src="http://oap.accuweather.com/launch.js"></script>' /
'</body></html>'
;
stop;
run;
%end;
%mend create_widgets;
%create_widgets;
Then I defined an InfoWindow and a custom marker for the Google map as:
put
'var info' i '= ''<iframe style="width:400px;height:360px;" src="widgets/accuweather_com_widget' i +(-1) '.html">'';' /
'var point' i '= new google.maps.LatLng(' lat ',' lng ');' /
'var marker' i '= new google.maps.Marker({' /
'position: point' i ',' /
'icon: ''images/weather-icon.gif'',' /
'map: map,' /
'title: "Click here for weather details"' /
'});' /
. . .
The rest of the code is no different than in all other Google Map with SAS series.
This widget makes use of document.write to inject style and markup .
write can't be used without possible undesired side-effects after a document has been loaded, but the infowindow opens after the document has been loaded.
Possible workaround:
Use a (hidden)iframe.
Into the hidden iframe load the widget and when the iframe has been loaded
set the content of the infowindow to the node representing the widget
apply the style created for the widget to the current document
//an array with the details, I guess ou want more than 1 marker
//[locationname, latitude, longitude, widget-url]
infos = [
['San Francisco', 37.770728, -122.458199, 'http://voap.weather.com/weather/oap/USCA0987?template=GENXH&par=3000000007&unit=0&key=twciweatherwidget'],
['Atlanta', 33.7489954, -84.3879824, 'http://voap.weather.com/weather/oap/USGA0028?template=GENXV&par=3000000007&unit=0&key=twciweatherwidget']
]
function initialize() {
var mapOptions = {
zoom: 3,
center: new google.maps.LatLng(44.3396955, -100.509996),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
//create the iframe
var infoframe = document.createElement('iframe');
document.body.appendChild(infoframe);
var infowindow = new google.maps.InfoWindow();
//iterate over the infos-array
for (var i = 0; i < infos.length; ++i) {
//create the marker
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(infos[i][1], infos[i][2]),
title: "Click here for the weather of \n" + infos[i][0],
script: infos[i][3]
});
//click-listener
google.maps.event.addListener(marker, 'click', function () {
var that = this;
infowindow.close();
//when the widget for this marker hasn't been parsed yet
if (!this.get('content')) {
//the window-object of the iframe
var win = infoframe.contentWindow;
google.maps.event.clearListeners(win, 'load');
//open document and write the widget-code
win.document.open();
win.document.write('\<script src="' + this.get('script') + '">\<\/script>');
//observe the load-event of the iframe
//will fire when widget is available
google.maps.event.addDomListener(win, 'load', function () {
//store style and widget-node as marker-properties
that.set('style', document.adoptNode(win.document.getElementsByTagName('style')[0]));
that.get('style').id = 'weatherstyle';
if (!document.getElementById('weatherstyle')) {
var weatherstyle = document.createElement('style');
weatherstyle.id = 'weatherstyle';
document.getElementsByTagName('head')[0].appendChild(weatherstyle);
}
that.set('content', document.adoptNode(win.document.body.firstChild));
//trigger the marker-click
//this will open the infowindow now
google.maps.event.trigger(that, 'click')
});
win.document.close();
}
//widget has been parsed, set infowindow-content and open it
else {
//inject widget-style into document
document.getElementById('weatherstyle').parentNode.replaceChild(that.get('style'), document.getElementById('weatherstyle'))
infowindow.setContent(that.get('content'));
infowindow.open(that.getMap(), that);
}
});
}
}
google.maps.event.addDomListener(window, "load", initialize);
Demo: http://jsfiddle.net/doktormolle/tvn4qtxL/
I initialize a google map here: (which is working fine, but I'll include for background)
this entire code comes inside of a .ejs file
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://maps.google.com/maps/api/js?sensor=true"></script>
<script type="text/javascript">
var map;
var loadMap = function() {
var myOptions = {
center: new google.maps.LatLng(39.952335, -75.163789),
zoom: 11,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
};
</script>
</head>
<body onload="loadMap()">
then when I try to iterate over my date to add my markers - I get an error (code works without this segment in it)
This is what I have so far:
Also note that because of express (I think it's express at least) I can use the <% code code code %> to write javascript inside of an html file.
<!-- data is an array of arrays [name, lat, lon, description, creator] -->
<% for (var i = 0; i < array[0].length; i++) {
var info = new google.maps.InfoWindow();
info.setContent( %><b><% "Name: "+array[0][i] %></b><% +". Description: "+array[3][i] %><i><% +". Creator: "+array[4][i] %></i><% );
var newCoords = new google.maps.LatLng(array[1][i], array[2][i]);
var marker = new google.maps.Marker({
position: newCoords,
map: map,
title: array[0][i],
if (message == array[0][i]) { // if the creator is currently signed in (his additions should be yellow on map)
icon: 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
}
});
google.maps.event.addListener(marker, 'click', (function(info, marker) {
return function() {
info.open(map, marker);};
})(info, marker))
}; %>
I'm getting a Unexpected Token : ';'
In case there's any confusion there I'm trying to add new markers for the data in my array, have it be clickable and display text in there that's partly bolded, partly italicized.
also, im using closure at the end there to make sure each event listener is unique (copied from here: Javascript: Looping through an array to create listeners, issue with call by reference and value?)
Hope eyes more experienced than I can spot my error or suggest a better alternative... I've tried taking out every single non-essential semi-colon but it accomplished nothing..
Syntax error, marker should be:
var marker = new google.maps.Marker({
position: newCoords,
map: map,
title: array[0][i],
icon : (message == array[0][i])? //use ternary
'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png'
: undefined
});
You can't have if statements in an object literal but you can assign icon with a ternary expression. If it's a problem that icon is undefined you can do it outside the object literal:
var info = new google.maps.InfoWindow(),
markerDetails;
//...code
markerDetails = {
position: newCoords,
map: map,
title: array[0][i]
};
if (message == array[0][i]) {
markerDetails.icon = 'http://maps.google.com/mapfiles/ms/icons/yellow-dot.png';
}
var marker = new google.maps.Marker(markerDetails);
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