Load Script and Execute only if needed - javascript

I need to find if there are any divs with class="map" in a page Code Pen Example.
If there are, and only in that case, load Google Maps API.
Then use it to load the maps into the divs using data attributes for lat and long values.
So I have the following:
<div class="map" data-long="51.5072" data-lat="0.1275">
Replace by map 1
</div>
<div class="map" data-long="74.0059" data-lat="40.7127">
Replace by map 2
</div>
I was considering using something like (this should be loaded only if map divs exist):
$.getScript('https://www.google.com/jsapi', function()
{
google.load('maps', '3', { other_params: 'sensor=false', callback: function()
{
}});
});
The code I would like to apply to each map is something like Google Maps Code:
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Thank You,
Miguel

See a solution for loading Google Maps API async:
https://stackoverflow.com/a/12602845/1491212
var gMapsLoaded = false;
window.gMapsCallback = function(){
gMapsLoaded = true;
$(window).trigger('gMapsLoaded');
}
window.loadGoogleMaps = function(){
if(gMapsLoaded) return window.gMapsCallback();
var script_tag = document.createElement('script');
script_tag.setAttribute("type","text/javascript");
script_tag.setAttribute("src","http://maps.google.com/maps/api/js?sensor=false&callback=gMapsCallback");
(document.getElementsByTagName("head")[0] || document.documentElement).appendChild(script_tag);
}
Then just do something like this :
$(document).ready(function(){
function initialize(){
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
$(window).bind('gMapsLoaded', initialize);
if($('.map').length){
window.loadGoogleMaps();
}
});

Related

latLng returns empty object- Google maps javascript API

I use a google map with javaScript and my code is :
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-12.043333,-77.028333);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
google.maps.event.addListener(map, "mousedown", function (e) {
//lat and lng is available in e object
var latLng = e.latLng;
console.log(latLng);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>`
The result of e.latLng is an empty object.
I tried to click the event, but the result is empty.
What should I do or change?
Your code is working fine :
Click on map and your coordinates will come in alert
Please check here

Google Maps Api not displaying map into div

This question has been asked a couple of times, but no response has worked for me. I tried to add width and height to container div
<div style="height:900px;width:1024px;">
Mapa
<div id="map" class="map"></div>
</div>
Tried either to add the domListener Event to google maps object or just using jquery document.ready function
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() { initialize(); });
I created this Jsfiddle to show my point, I know that I am missing the API key but this doesn't seems to be the problem.
I don't know what I am missing here. Any ideas?
I know that I am missing the api key
Snippet with code Below
function initialize(){
$(".map").each(function(){
var centerLat = 52.5230809;
var centerLong = 13.3999976;
console.log(centerLat);
console.log(centerLong);
var centerLatLong = new google.maps.LatLng(centerLat, centerLong);
var mapOptions = {
center: { lat: parseFloat(centerLat), lng: parseFloat(centerLong)},
zoom: 8,
scrollwheel: false,
draggable:true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
console.log(map);
var marker = new google.maps.Marker({
position: centerLatLong,
map: map
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
$(document).ready(function() { initialize(); });
<div style="height:900px;width:1024px;">
Mapa
<div id="map" class="map"></div>
</div>
You should add css to map div.
<div style="height:900px;width:1024px;">
Mapa
<div style="height:900px;width:1024px;" id="map" class="map"></div>
</div>
As #egvrcn 's answer. But why are you using .each() ? You want to use multiple maps ?
Yes ?
function initialize() {
$(".map").each(function () {
var $this = $(this);
// ...
var map = new google.maps.Map($this[0], mapOptions);
// ...
});
}
No ?, so do just...
function initialize() {
// ...
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
// ...
}

Move google map center point onclick

I have initialized the Google Maps load function, and it works fine. There are also multiple markers with clusters. I haven't put markers and cluster codes here. Those are standard code. My code:
jQuery(document).ready(function(){
initialize();
});
function initialize() {
var center = new google.maps.LatLng(59.875405, 10.842099);
var zoom = 10;
var map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: zoom,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function mapAnimate(){
var map = google.maps.Map(document.getElementById("map-canvas"));
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
window.setTimeout(function() {
map.panTo(new google.maps.LatLng(58.9633, 5.7189));
}, 500);
});
}
Then I want to move the map to another center position without re-generating the map. There is a link which calls the function mapAnimate().
HTML:
test
But it does not work. I get an error like this:
TypeError: c[Eb] is not a function......
Actually I don't get the map instance.
Declare your map variable outside the functions. That should do the trick.
jQuery(document).ready(function(){
initialize();
});
var map;
function initialize() {
var center = new google.maps.LatLng(59.875405, 10.842099);
var zoom = 10;
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: zoom,
center: center,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function mapAnimate(){
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
window.setTimeout(function() {
map.panTo(new google.maps.LatLng(58.9633, 5.7189));
}, 500);
});
}
But if you call the mapAnimate() function from a click event, I don't see why you would need that listener on the map object.

Unable to add marker in Google Maps Api v3

Since yesterday I'm trying to add marker in Google Maps Api v3 . I read the documentation and all. Here's my code :
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(28.63, 77.21),
zoom: 8,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
// google.maps.event.addDomListener(window, 'load', initialize);
function getFillingDetails(){
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
var lat = [];
var lon = [];
var price = [];
$.each(data, function(key, value){
lat.push(value.latitude);
lon.push(value.longitude);
price.push(value.price);
});
});
var myLatlng = new google.maps.LatLng(23.72,77.10);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map,
});
}
</script>
Everything looks fine to me. The initialize() function is called after onload of body tag.
And getFillingDetails() function is called when I click a button.
But still I'm getting no success.
You have a syntax error at:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map, <--- get rid of this comma
});
next time you should look in the developer console for any errors.
// To add the marker to the map, call setMap();
marker.setMap(map);
source : https://developers.google.com/maps/documentation/javascript/markers

How to embed google map?

I am trying to add a Google Map to my website, and I tried this:
$.getScript("https://maps.googleapis.com/maps/api/js?sensor=false", function () {
alert("1");
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
alert("2");
map = new google.maps.Map(document.getElementById("container"), myOptions);
});
This is not working. Can anybody tell me why?
EDIT
Script loaded perfectly. I know this because alert(1) shows but after that control does not reach alert(2).
document.getElementById(id)
What is id, where did that get defined?
Also getScript is for doing Ajax requests, which isn't really how you should be doing Google Maps. Just call the script in the normal way, and have an init function which executes on document ready. Or even better use the window.load event listener that the Google Maps API provides for you anyway.
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?sensor=false" />
<script type="text/javascript">
function init(id)
{
var map;
var myOptions = {
zoom: 8,
center: new google.maps.LatLng(-34.397, 150.644),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById(id), myOptions);
}
google.maps.event.addDomListener(window, 'load', init('yourDivID'));
</script>
You have to use async loading for this - https://developers.google.com/maps/documentation/javascript/tutorial#asynch
In the current approach, the script do this-
function getScript(src) {
document.write('<' + 'script src="' + src + '"' + ' type="text/javascript"><' + '/script>');
}
So, when you call $.getScript, that will goto void. And, google.maps.LatLng becomes undefined.
I've created a version with the async one. You can check the fiddle # http://jsfiddle.net/rifat/G3yPw/
You should have a look on your container div.
It must have specified width and height.
And I used to separate the affectation of LatLng :
var map;
var ll = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: ll,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("container"), myOptions);

Categories