Google Map inside modal not showing - javascript

I have a modal where when it is clicked the map show up, but the map is not working but instead a gray image is shown.
<button class="btn" data-toggle="modal" data-target="#myModal" onclick="resize()">Show Modal</button>
<!--MODAL-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Warning!</h4>
</div>
<div class="modal-body" id="modal-body">
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map" style="width: 580px; height:400px"></div>
</div>
<div class="modal-footer" id="modal-footer">
</div>
</div>
</div>
</div>
my srcipt is from google auto complete places, when the map is not inside the modal, it is working perfectly fine.
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
function resize(){
$('#myModal').on('shown', function () {
google.maps.event.trigger(map, "resize");
});
}
</script>
I tried doing this Similar Question but it is giving me
Uncaught ReferenceError: $ is not defined
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function () {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function (marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function (place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
$(document).ready(function () {
$('#myModal').on('shown', function () {
google.maps.event.trigger(map, "resize");
});
});
<!DOCTYPE html>
<html>
<body>
<body>
<button class="btn" data-toggle="modal" data-target="#myModal"/>Show Modal</button>
<!--MODAL-->
<div id="myModal" class="modal fade" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Warning!</h4>
</div>
<div class="modal-body" id="modal-body">
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map" style="width: 580px; height:400px"></div>
</div>
<div class="modal-footer" id="modal-footer">
</div>
</div>
</div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyADR3ipXgTLZd7uIcl3NBUujxF3kKp9rFk&libraries=places&callback=initAutocomplete"
async defer></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</body>
</html>

var map;
function initAutocomplete() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -33.8688, lng: 151.2195},
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// ....
}
$(function() {
$('#myModal').on('shown', function () {
google.maps.event.trigger(map, "resize");
});
});
You have wrapped
google.maps.event.trigger(map, "resize");
inside function resize() {} that is never executed. Try wrapping it with jQuery's $(document).ready(function(){}); instead.

This kind fo error ($ is not defined) means that you have not initialized a javascript library in your code.
and as you are using:
$('#myModal').on('shown', function () {
google.maps.event.trigger(map, "resize");
});
you need to add jquery at the top of your script. Something like this:
You may find information here: w3schools jquery init
Start by solving the js error and possibly the map will load.

Related

Throttling or delaying Google Places API autosuggestions

Google Places API Web Service has a 1000 request per day quota limit for non-billed accounts. When using the search box autosuggestion feature providing multiple places for each key press, this limit will be reached fairly quickly.
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div style="height:100%; width:100%;position:absolute;">
<div id="map"></div>
</div>
<script>
window.onload = initAutocomplete;
function initAutocomplete() {
var my_position = new google.maps.LatLng(51.163375, 10.447683);
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 51.163375, lng: 10.447683},
disableDoubleClickZoom: true,
zoom: 9,
mapTypeId: 'roadmap'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
var crowdMarker = new google.maps.Marker({
position: my_position,
map: map
});
google.maps.event.addListener(map, 'dblclick', function(e){
var positionDoubleClick = e.latLng;
crowdMarker.setPosition(positionDoubleClick);
var lat = crowdMarker.getPosition().lat();
var lng = crowdMarker.getPosition().lng();
});
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
google.maps.event.addDomListener(searchBox, 'keydown', function (e) {
if (e.keyCode == 13) {
e.preventDefault();
}
});
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=myAPIKey&libraries=places"
async defer></script>
Things I've tried include setting a bound to the SearchBox to limit the suggestions to a set area, as well as adding a delay within the keydown section.
Can anyone suggest a way to be able to throttle or delay the autosuggestion appearing, and therefore sending fewer requests?
I'm afraid the current implementation of autocomplete and search box in places library of Maps JavaScript API doesn't allow to throttle or delay requests programmatically. You can see a feature request in Google issue tracker for this:
https://issuetracker.google.com/issues/35823678
Please star this feature request to add your vote. The only workaround I can think of is implementing your own autocomplete element that uses a google.maps.places.AutocompleteService class and where you will be able to control a frequency of requests sent to AutocompleteService.
https://developers.google.com/maps/documentation/javascript/reference#AutocompleteService

geolocation-marker.js conflict with markerclusterer.js

I have a map but conflict. when I click or zoom the marker, all marker disappear. but when I remove the marker clusterer all fine, but so many marker. I use geolocation-marker.js & markerclusterer.js. any ide for this problem? thanks
My HTML
<div style="width:100%; height:100%;">
<div id="map">
<span style="color:Gray;">
<img style="margin: 0px auto; display: block; width: 50%;" src="images/circle-loading-animation.gif"></img>
</span>
</div> </div>
</div><!-- Map Ends display -->
This is my Java script geolocation-marker
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
//marker follow & center screen
navigator.geolocation.watchPosition(function(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var geolocpoint = new google.maps.LatLng(latitude, longitude);
map.setCenter(geolocpoint);
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
And this my script markerclusterer
//markerCluster
var mcOptions = {
gridSize: 50,
maxZoom: 15
};
var markerCluster = new MarkerClusterer(map, [], mcOptions);
.....................................................
....................................................
markerCluster.addMarker(marker, true);
I find the Conflict, it's because I add <script src="https://maps.googleapis.com/maps/api/js"></script> in head. And when I click or zoom the marker, all marker disappear. But when I change the url above to script src="http://maps.googleapis.com/maps/api/js?v=3.exp&libraries=places&sensor=true"></script> all marker it's fine.
Thanks

How to pass an ENV variable into script tag

I'm trying to pass my api key which is in my application.yml file into a js script tag for google maps, is this possible? If not, what is the best way to handle this? Also, I'm using the Figaro gem to store ENV variables. Thanks in advance.
<% if #location.latitude.present? && #location.longitude.present? %>
<script>
var myLatLng = {lat: <%= #location.latitude %>, lng: <%= #location.longitude %>};
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'), {
center: myLatLng,
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: '<%= #location.name %>'
});
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
// Bias the SearchBox results towards current map's viewport.
map.addListener('bounds_changed', function() {
searchBox.setBounds(map.getBounds());
});
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds();
places.forEach(function(place) {
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
</script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js.erb?key=MAPS_API_KEY&libraries=places&callback=initAutocomplete"
async defer></script
<% end %>
Error
https://maps.googleapis.com/maps/api/js.erb?key=&libraries=places&callback=initAutocomplete
This is what I have and it gives me the error I posted, if I put the Key in directly it works.
<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%= ENV['MAPS_API_KEY'] %>&libraries=places&callback=initAutocomplete"
async defer></script
This worked for me:
<script async defer src=<%="https://maps.googleapis.com/maps/api/js?key=#{ENV['GOOGLE_MAPS_API_KEY']}&callback=initMap"%> type="text/javascript"></script>
You should be able to treat it as any other ENV variable using ERB:
...
<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%=ENV['MAPS_API_KEY']%>&libraries=places&callback=initAutocomplete"
async defer></script>
Try this #{ENV['MAPS_API_KEY']}, I had a similar issue before:
<script src="https://maps.googleapis.com/maps/api/js.erb?key=<%=#{ENV['MAPS_API_KEY']}%>&libraries=places&callback=initAutocomplete" async defer></script>
I guess you just dont wanna put your api_key into a html tag and make your key vulnerable. You can try following code under your index.html, it works for me.
<div id="google">
<script type="text/javascript">
import {
GOOGLE_MAP_API
} from "<the location you save your apikey>";
function changeSrc() {
document.getElementById("google").src = `https://maps.googleapis.com/maps/api/js?key=${GOOGLE_MAP_API}`
}
</script>
</div>
Note that if you're not using Ruby (or Figaro) and you're using Webpack, you can inject it via the HtmlWebpackPlugin.
You can use a data tag to pass env variables
<script id="div" data-key="<%=ENV['MAPS_API_KEY']%>">
const div = document.getElementById("div");
console.log(div.dataset.key);
</script>

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.

How to Display Multiple Google Maps per page with API V3

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

Categories

Resources