JS function not being reached - javascript

I have a JavaScript file to work with Google JavaScript API for maps however the function is not doing anything its like its not being reached any help is appreciated thanks
window.onload = function() {
alert("Hi!");
var map;
function initMap() {
alert("Function reached!");
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
}
}

try executing your initMap function afterwards (or when it is needed)
window.onload = function() {
alert("Hi!");
var map;
function initMap() {
alert("Function reached!");
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 8
});
};
initMap();
}

Related

Iterate through map markers

I want to put markers to the specific cities that I chose but I need to do it in a for loop, manually going through the process is time-consuming and looks quite ugly on the code. Any tips to use a for loop correctly? What am I doing wrong here?
var izmir = {lat: 38.4237, lng: 27.1428};
var amsterdam = {lat: 52.3680, lng: 4.9036};
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {zoom: 4,
center: izmir});
var map = new google.maps.Map(document.getElementById('map'), {zoom: 4,
center: amsterdam});
var i;
for(i=0;i.length;i++)
{
nokta = new google.maps.Marker({position: izmir,amsterdam, map: map});
}
}
EDIT: I guess I've partly achieved what I wanted, only problem is that the marker is only used by the last entry, in this case it's Prague. If I change it to another city (e.g. Amsterdam), map is centered on Amsterdam and the marker is only used by Amsterdam. How can I use the marker on all?
var sehirler = {
'izmir': {lat: 38.4237, lng: 27.1428},
'amsterdam': {lat: 52.3680, lng: 4.9036},
'prague': {lat: 50.0755, lng: 14.4378}};
function initMap() {
for (var sehir in sehirler)
{
var map = new google.maps.Map(document.getElementById('map'),
{zoom: 4, center: sehirler[sehir]});
var marker = new google.maps.Marker({position: sehirler[sehir], map: map});
}
}
EDITED based on discussion below
is this what you're looking for?
// initialize object containing all cities
var sehirler = {
izmir: { lat: 38.4237, lng: 27.1428 },
amsterdam: { lat: 52.368, lng: 4.9036 },
prague: { lat: 50.0755, lng: 14.4378 }
};
function initMap() {
// initialize main map
var center = sehirler.CITY // <-- edit CITY to be the correct city
var map = new google.maps.Map(document.getElementById('map'), { zoom: 4, center: center });
// iterate throughout cities to put all markers on same map
for (var sehir in sehirler) {
var marker = new google.maps.Marker({ position: sehirler[sehir], map: map });
}
}

Google Map APIs - Combining geolocation and cluster markers

I am creating a website for ad classifies. I would like the users to see where the location of the item is on a map near their location.
Using Google's JS code templates for Geolocation and Cluster Markers work separately, when added to the same JS, they don't work. Is there a way to combine the JS for them to work on the same map?
Thanks in advance
Edit - I have added the JS codes
/* Geolocation */
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
/* Map Clustering */
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 55.378052, lng: -3.435973}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 55.633792, lng: -4.661550},
{lat: 55.864239, lng: -4.251806},
{lat: 55.614302, lng: -4.665554},
{lat: 55.543781, lng: -4.664010},
{lat: 55.551993, lng: -4.623667},
{lat: -26.246920, lng: -4.523914}
]
It is a bit difficult to answer your question without any specific samples. you will need to combine the geolocation JS code onto the cluster markers, which is an obvious answer. So if you have a sample of your code, we will be able to help.

Javascript passing values from external functions to internal functions

I have three javascript functions.
The main function is within script tags in my index.html file.
I have two other functions that are in an external file named cities.js.
Beneath is the main function found within the script tags:
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: coords,
mapTypeId: 'terrain'
}
This is for the Google Maps API.
The next two functions hold the coordinates for the map.
function ldn() {
var coords = var coords = {lat: 51.509865, lng: -0.118092};
}
function birm() {
var coords = {lat: 52.509865, lng: -0.2};
}
Essentially, I have a drop down box and when either 'ldn' or 'birm' is clicked, the functions in the external file are executed depending on which one is clicked.
I wish to take the coordinates within the functions and include them into the main function for the 'center' variable.
I hope this makes sense! I have tried calling the function in center (center: birm()) but it does not work as intended. Simply returning the coords doesn't work either.
If you want to change the Map object with the click of a button and it doesn't have a method to do so, you have to recreate it.
With the code below the map gets initialised to the new position using your functions:
var defaultCoords = {
lat: 52.509865,
lng: -0.2
}
function initMap(coords) {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: coords || defaultCoords,
mapTypeId: 'terrain'
});
}
function ldn() {
var coords = {
lat: 51.509865,
lng: -0.118092
};
initMap(coords);
}
function birm() {
var coords = {
lat: 52.509865,
lng: -0.2
};
initMap(coords);
}
But if there is a method to apply new coordinates (.setCenter()) to the map you have to store the object outside of initMap():
var defaultCoords = {
lat: 52.509865,
lng: -0.2
}
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: defaultCoords,
mapTypeId: 'terrain'
});
}
function ldn() {
var coords = {
lat: 51.509865,
lng: -0.118092
};
map.setCenter(coords);
}
function birm() {
var coords = {
lat: 52.509865,
lng: -0.2
};
map.setCenter(coords);
}
The initMap is only run once to initialize the map.
If you want to recenter it later based on your choices use
function ldn() {
var coords = {lat: 51.509865, lng: -0.118092};
map.setCenter(coords);
}
function birm() {
var coords = {lat: 52.509865, lng: -0.2};
map.setCenter(coords);
}
This assumes that the map variable is global.

Google map not displaying HTML (Javascript)

Not sure why the google map cannot display
HTML Code
<div id="map" style="width:400px;height:600px;"></div>
<script>
function initMap() {
var location = { lat: 1.275699, lng: 103.845802 };
var map = new goole.maps.Map(document.getElementByID("map"), {
zoom: 5
center: location})
var marker = new google.maps.Marker({ position: myCenter });
marker.setMap(map);
});
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCwXow-YSSaavXynAkBF1TkpAPKijAC-Qk&callback=initMap"></script>
I haven't added any CCS code for the map.
there are syntax errors in your code I have corrected them ref
<div id="map" style="width:400px;height:600px;"></div>
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCwXow-YSSaavXynAkBF1TkpAPKijAC-Qk&callback=initMap" async defer></script>

Generate Google Maps with dynamic values of latitude and longitude in javaScript

I am gone through many tutorials and the Google Developer site, but everywhere the way to create Google Maps with a particular latitude/longitude are given.e.g.
function initialize() {
var mapOptions = {
center: {
lat: -34.397,
lng: 150.644
},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
Does anyone know the JavaScript code to create the map based on dynamic values lat/long? I mean not specific values like -34.397 etc. To the function initialize I will pass the latitude and longitude arguments and generate the map. Can anyone please tell me how to do it?
If you're going to pass in values for lat/lng as arguments for the initialize function couldn't you do:
function initialize(lat, lng) {
var mapOptions = {
center: { lat: lat, lng: lng},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize.bind(null, <Lat>, <Lng>));
Pass the lat, lng to your function as parameters and call your function with the right values initialize(-34.397, 150.644)
function initialize(lat, lng) {
var mapOptions = {
zoom: 4,
center: new google.maps.LatLng(lat, lng),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize(-34.397, 150.644));
try with this:
function initialize(lat, lng){
return new wrapperGM(lat,lng).initialize;
}
function wrapperGM(lat, lng) {
this.initialize=function() {
var mapOptions = {
center: {
lat: lat,
lng: lng
},
zoom: 8
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
}
google.maps.event.addDomListener(window, 'load', initialize(56, 8));
hope this helps.
regards
Use gmap4rails gem
and in your controller
def map
#hash = Gmaps4rails.build_markers(#towns) do |town, marker|
marker.lat town.master_geo_town.latitude
marker.lng town.master_geo_town.longitude
marker.infowindow render_to_string(:partial => "infomap", :locals=> { :town => town.master_geo_town})
end
and in your view
<div id="multi_markers" style='width:100%;height: 400px;'> </div>
<script>
handler = Gmaps.build('Google');
handler.buildMap({ internal: {id: 'multi_markers'}}, function(){
var json_array = <%=raw #hash.to_json %>;
var markers = handler.addMarkers(json_array);
_.each(json_array, function(json, index){
json.marker = markers[index];
});
createSidebar(json_array);
handler.bounds.extendWith(markers);
handler.fitMapToBounds();
});
});
</script>

Categories

Resources