Related
I have a google map with a kml layer. The KML layer has a few markers on it. So far, i've managed to insert a button into the kml layer infowindow on click. I'm trying to add a marker at the place where it is clicked. I can do this just fine without kml layers. My click event calls an "addMarker" function which places the markers. I have a button in the infowindow which, when clicked, should add a marker at that point.
This is what i've done so far:
google.maps.event.addListener(layers[1], 'click', function(kmlEvent) {
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += '<br/><button onclick="kmladd()" class="btn btn-success btn-sm">Add to Route</button>';
showInContentWindow(text);
});
function kmladd(){
addMarker(kmlEvent.latLng);
}
function showInContentWindow(text) {
var sidediv = document.getElementById('content-window');
}
function addMarker(location) {
var marker = new google.maps.Marker({
map: map,
position: location,
draggable:true,
icon: getMarkerIcon()
});
marker.identifier = 'waypoint_'+currentIndex;
markers.push(marker);
}
I get an "Uncaught ReferenceError: kmladd is not defined" error. Is it possible to call a function on buttonclick of an infowindow?
Any assistance would be greatly appreciated.
The kmladd function needs to be in the global namespace to be used as an HTML onclick function.
proof of concept fiddle
code snippet:
var lastKmlEvent;
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: 41.876,
lng: -87.624
}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml',
map: map
});
google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
lastKmlEvent = kmlEvent;
var text = kmlEvent.featureData.name;
kmlEvent.featureData.infoWindowHtml += '<br/><button onclick="kmladd()" class="btn btn-success btn-sm">Add to Route</button>';
});
}
function addMarker(latLng) {
var marker = new google.maps.Marker({
position: latLng,
title: latLng.toUrlValue(6),
map: map
});
}
function kmladd() {
addMarker(lastKmlEvent.latLng);
}
google.maps.event.addDomListener(window, "load", initMap);
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>
I have problem with putting marker on map. I have model Location where i save coordinates x and y. I read from base all coordinates in list and send that list in view. Than I tried to go trought all list and put markers on loc. But it doesnt work. Here is my code.
#(places: java.util.List[models.Location])
#adminmain("Post Offices") {
<ol class="breadcrumb">
<li>Admin Panel</li>
<li>Maps</li>
<li class="active">Location</li>
</ol>
<h1>Maps</h1
<div class="templatemo-maps">
<div class="row">
<div class="col-md-12 col-sm-12 margin-bottom-30">
<div id="map" style="position: relative; height: 700px; width: auto"></div>
AND SCRIPT
<script type="text/javascript">
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 5,
center: new google.maps.LatLng(43.8331, 18.3039),
mapTypeId: google.maps.MapTypeId.ROADMAP});
var i;
for(i = 0; i<#places.size(); i++){
var marker = new google.maps.Marker({
position: new google.maps.LatLng(#places.get(i).x,#places.get(i).y),
map: map
});
}
map.addListener('center_changed', function() {
// 3 seconds after the center of the map has changed, pan back to the marker
window.setTimeout(function() {
map.panTo(marker.getPosition());
}, 3000);});
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(marker.getPosition());
});
If anyone have problem with this I found solution. U must write for each statement from scala lang. Like this:
#for(place <- places) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(#place.x
, #place.y),
map: map
});
}
And it works!
I know this is a common problem here, i already look at all the topics here for a solution, but still, when i change tabs i continue with this problem:
please take a look at my js code:
function initialize() {
//replace 0's on next line with latitude and longitude numbers from earlier on in tutorial.
var myLatlng = new google.maps.LatLng(40.654372, -7.914174);
var myLatlng1 = new google.maps.LatLng(43.654372, -7.914174);
var myOptions = {
zoom: 16,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var myOptions1 = {
zoom: 16,
center: myLatlng1,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
//here's where we call the marker.
//getElementById must be the same as the id you gave for the container of the map
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var map1 = new google.maps.Map(document.getElementById("map_canvas1"), myOptions1);
//google.maps.event.trigger(map1, 'resize');
//map1.setCenter(myLatlng1);
var marker = new google.maps.Marker({
position: myLatlng,
title:"ADD TITLE OF YOUR MARKER HERE"
});
var marker1 = new google.maps.Marker({
position: myLatlng1,
title:"ADD TITLE OF YOUR MARKER HERE"
});
var contentString = '<div id="content">'+
'<div id="siteNotice">'+
'<\/div>'+
'<h2 id="firstHeading" class="firstHeading">ADD TITLE HERE<\/h2>'+
'<div id="bodyContent">'+
'<p style="font-size:1em">ADD DESCRIPTION HERE<\/p>'+
'<\/div>'+
'<\/div>';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(marker1, 'click', function() {
infowindow.open(map1,marker1);
});
google.maps.event.addListener(map, "idle", function(){
marker.setMap(map);
});
google.maps.event.addListener(map, "idle", function(){
marker1.setMap(map1);
});
// To add the marker to the map, call setMap();
google.maps.event.addListenerOnce(map, 'idle', function() {
google.maps.event.trigger(map, 'resize');
map.setCenter(myLatlng); // be sure to reset the map center as well
});
google.maps.event.addListenerOnce(map1, 'idle', function() {
google.maps.event.trigger(map1, 'resize');
map1.setCenter(myLatlng1); // be sure to reset the map center as well
});
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
i have two maps, one ofr each tab. i could solve the problem of the center point being hide on the left corner with this from other post:
.ui-tabs .ui-tabs-hide { /* my_tabs-1 contains google map */
display: block !important;
position: absolute !important;
left: -10000px !important;
top: -10000px !important;
}
but the problem stated here i had no luck even lookin at other topics here.
I found the clean solution:
<script type="text/javascript">
function showAddressMap(){
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
geocoder = new google.maps.Geocoder();
// searchQuery is the address I used this in a JSP so I called with $
geocoder.geocode( {'address': "${searchQuery}"}, 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);
}
});
google.maps.event.trigger(map, 'resize');
//}
}
JQ(document).ready(function(){
JQ('#tabs').tabs();
JQ('#maptab').bind('click', function() {
showAddressMap();
});
});
</script>
<div id="tabs">
<li><fmt:message key="fieldset.map"/></li>
</div>
<div id="tabs-1">
<fieldset>
<div id="map_canvas" style="height:500px; width:100%;"></div>
</fieldset>
</div>
You need to set the center and trigger a re-size event.
MyMap.setCenter(MyCenterCoords);
google.maps.event.trigger(MyMap, 'resize');
This code google.maps.event.trigger(map, 'resize') should be in the pageshow like below.
$('#map_result').live('pageshow',function(event){
google.maps.event.trigger(map, 'resize');
});
By the way, have you found the solutions for this? I actually make it works using css.
I know its not a elegant solution, but you can just add an Iframe inside each tab. and when you click the tab, the map load with the correct sizes.
I'm using Twitter's Bootstrap for defining my CSS. I have made a page with three tabs. The second tab contains a map built with Google Maps. However when opening the page and switching to the second page with the map, the map is not rendered completely. Once I reload the page with the google maps tab as the selected tab the map loads entirely.
I read some posts that advised people with the same problem to add the following code to the javascript:
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
However this doesn't seem to be the solution. Please find the complete code below:
Javascript:
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
}
</script>
HTML:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
</div>
How can I resolve this? Maybe I can add some javascript that reloads the google maps part once the tab is selected but I don't know how to do this....
Updated code still shows the error:
<div class="tab-pane" id="orange" style="background-color:#E3F2FF;">
<div id="map_canvas" style="width:780px; height:400px; overflow:;"></div>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript" src="util.js"></script>
<script type="text/javascript">
function initialize() {
google.maps.event.addDomListener(window, 'resize', function() {
map.setCenter(homeLatlng);
});
var myLatlng = new google.maps.LatLng(37.4419, -122.1419);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
downloadUrl("data.xml", function(data) {
var markers = data.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var latlng = new google.maps.LatLng(parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var marker = new google.maps.Marker({position: latlng, map: map});
}
});
map.checkResize();
}
</script>
</div>
I was battling with this issue as well. I was using a modal form and it rendered the map when it was hidden. When the tab is shown, you need to trigger this code:
google.maps.event.trigger(map, 'resize');
map.setZoom( map.getZoom() );
Hopefully it will work for you. If that doesn't work, here is the link where I found the solution. Maybe there will be another helpful comment.
http://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
There's a lot of solutions here and frankly they're all wrong. If you have to hi-jack the default functionality of Bootstrap tabs, you might as well not use Bootstrap tabs. If you're only calling resize after the tab is shown, you may still have issues with the GMaps interface (zoom level and such). You simply have to initialize the map after the tab is visible.
var myCenter=new google.maps.LatLng(53, -1.33);
var marker=new google.maps.Marker({
position:myCenter
});
function initialize() {
var mapProp = {
center:myCenter,
zoom: 14,
draggable: false,
scrollwheel: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map=new google.maps.Map(document.getElementById("map-canvas"),mapProp);
marker.setMap(map);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map, marker);
});
};
$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
initialize();
});
You can see a working example in this bootply: http://www.bootply.com/102241
Note: if your interface is still glitchy, it could be this issue:
Google Maps API V3 : weird UI display glitches (with screenshot)
Using the most recent gmaps api, you just need to add this to your styling:
.gm-style img { max-width: none; }
.gm-style label { width: auto; display: inline; }
Works for me after testing different delays :
$(window).resize(function() {
setTimeout(function() {
google.maps.event.trigger(map, 'resize');
}, 300)
});
Hope it helps.
I have solved the problem by using
google.maps.event.trigger(map, 'resize');
inside show function in bootstrap-tab.js means at the time of showing the box you should trigger resize event and will work..
Edit: I have seen another link with the same answer
Google Maps API v3, jQuery UI Tabs, map not resizing
I have seen this link after solving the problem to find out the reason which is still unanswered that why resize event does not works on the click event of the tabs but works in the tab js
this works fine for me, I use jquery tabs
setTimeout(function() {
google.maps.event.trigger(map, "resize");
map.setCenter(new google.maps.LatLng(default_lat, default_lng));
map.setZoom(default_map_zoom);
}, 2000);
from this link https://code.google.com/p/gmaps-api-issues/issues/detail?id=1448
To show a google maps in a hidden div, the div must show before the map is created and loaded. Below is an example:
<div id="map_canvas" style="width:500px; height:500px"></div>
<script>
$(document).ready(function(){
$('#button').click(function() {
$('#map_canvas').delay('700').fadeIn();
setTimeout(loadScript,1000);
});
});
function initialize() {
var title= "Title";
var lat = 50;
var lng = 50;
var myLatlng = new google.maps.LatLng(parseFloat(lat),parseFloat(lng));
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
position: myLatlng,
title:artTitle
});
// To add the marker to the map, call setMap();
marker.setMap(map);
}
function loadScript() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.google.com/maps/api/js?sensor=false&callback=initialize";
document.body.appendChild(script);
}
</script>
For me, what it worked was to call the function that renders the map after the, in my case, the modal had shown.
All I had to do was:
$(document).on("shown", "#eventModal", function(){
bindMap(coordinates);
});
You can do the same with the tabs, because they also have a "shown" event.
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