Javascript passing values from external functions to internal functions - javascript

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.

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 });
}
}

Try to create a cluster unsing a sample but addLayer got undefined

Here API clustering error: "addLayer is not defined"
Error I am calling the function startClustering, but I get a error map.addLayer is undefined.
I think maybe the map object lost the context scope, but how can I could pass the right scope to have access to addLayer function from the map.
//Boilerplate map initialization code starts below:
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(document.getElementById('map'),
defaultLayers.normal.map, {
center: {
lat: -19.9211375,
lng: -43.9490617,
},
zoom: 6
});
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
// create default UI with layers provided by the platform
var ui = H.ui.UI.createDefault(map, defaultLayers, 'pt-BR');
function startClustering(map, data) {
var dataPoints = data.map(function (item) {
return new H.clustering.DataPoint(item.coords.lat, item.coords.lng);
});
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {
eps: 32,
minWeight: 2
}
});
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(clusteringLayer);
}
startClustering(map, travelData);
I was not able to reproduce the "addLayer is not defined" error you observed. Since you did not provide a full listing (for example, travelData is not defined), I suspect the issue may not be demonstrated in the code sample to help you debug.
It looks like you followed the clustering example from the documentation:
https://developer.here.com/api-explorer/maps-js/v3.0/clustering/marker-clustering
There is no need to wrap it in a function though if you suspect a scoping issue. For example this works for me:
var platform = new H.service.Platform({
'app_id': 'your-app-id',
'app_code': 'your-app-code',
});
var defaultLayers = platform.createDefaultLayers();
var map = new H.Map(
document.getElementById('map'),
defaultLayers.normal.map, {
center: {lat: -19.9211375,
lng: -43.9490617},
zoom: 6,
});
var behavior = new H.mapevents.Behavior(new H.mapevents.MapEvents(map));
var ui = H.ui.UI.createDefault(map, defaultLayers, 'pt-BR');
var travelData = [
{lat: -19.8211, lng: -43.9490617},
{lat: -19.7211, lng: -43.9490617},
{lat: -19.6211, lng: -43.9490617},
{lat: -19.5211, lng: -43.9490617},
{lat: -19.4211, lng: -43.9490617},
{lat: -19.3211, lng: -43.9490617},
];
var dataPoints = travelData.map(function(item) {
return new H.clustering.DataPoint(item.lat, item.lng);
});
var clusteredDataProvider = new H.clustering.Provider(dataPoints, {
clusteringOptions: {eps: 32, minWeight: 2 }
});
var clusteringLayer = new H.map.layer.ObjectLayer(clusteredDataProvider);
map.addLayer(clusteringLayer);
It's not exactly the same as I simplified travelData a bit so it may depend on your dataset. Also make sure you are including the mapjs-clustering.js script in your HTML, though you'd see an error like "H.clustering is undefined" if that were the issue.

Google Maps API Event Listener For Marker

I have created three markers using Google Maps API. Is there a way that I can add an event listener to each marker so that they will work independently when the corresponding marker is active? I would like to display a message if the user is getting closer to a marker, specifically with bounds_changed. I want to continue giving the user a message until they get to a zoom level of say 5.
<script>
var map;
var score;
score = 0;
function initMap() {
var chicago = {lat: 41.8781, lng: -87.6298};
var indianapolis = {lat: 39.7684, lng: -86.1581};
var oklahomaCity = {lat: 35.4819, lng: -97.5084};
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 0.0, lng: 0.0},
zoom: 1
});
var chicagoMarker = new google.maps.Marker({
position: chicago,
});
var oklahomaCityMarker = new google.maps.Marker({
position: oklahomaCity,
});
var indianapolisMarker = new google.maps.Marker({
position: indianapolis,
});
if (score==0) {
chicagoMarker.setMap(map)
}
if (score==1) {
oklahomaCityMarker.setMap(map)
}
if (score==2) {
indianapolisMarker.setMap(map)
}
chicagoMarker.setVisible(false);
indianapolisMarker.setVisible(false);
oklahomaCityMarker.setVisible(false);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCuvsCAF0gVmwv6AF0SoA3xBjV66RG4r7o&callback=initMap"
async defer></script>
try this
google.maps.event.addListener(chicagoMarker, 'click', function(){
//do something
})

Show marker on Google Maps Javascript external link

On the Google Maps javascript, there is a clickable link at the bottom left of the map with the Google icon to "See this area on Google Maps". This link opens up Google Maps, however, it only centers on the latitude/longitude provided and doesn't show the marker I provide to the API.
function initMap() {
map = new google.maps.Map(document.getElementById('gmap_holder'), {
center: {lat: 37.423021, lng: -122.083739},
zoom: 15
});
map.setOptions({draggable: false, zoomControl: true, scrollwheel: false, disableDoubleClickZoom: true});
var coord = new google.maps.LatLng(37.423021, -122.083739);
var marker = new google.maps.Marker({
position: coord,
map: map
});
}
I know there is a way to produce an URL that will show a marker, such an example would be http://maps.google.com/maps?q=loc:36.26577,-92.54324, but I can't seem to figure out from the API.
Should be:
function initMap() {
var center = {lat: 37.423021, lng: -122.083739};
var map = new google.maps.Map(document.getElementById('gmap_holder'), {
zoom: 4,
center: center
});
var marker = new google.maps.Marker({
position: center,
map: map
});
// you can set other options
}
More info:
You can find required properties here: MapOptions
Example: Simple markers
EDIT:
#Sefam, I edited your code because I saw some difference with example. I edited my answer to show where is the difference.
function initMap() {
var map = new google.maps.Map(document.getElementById('gmap_holder'), {
center: {lat: 37.423021, lng: -122.083739}, // or try:
// center: new google.maps.LatLng(lat: 37.423021, lng: -122.083739),
zoom: 15
});
map.setOptions({draggable: false, zoomControl: true, scrollwheel: false, disableDoubleClickZoom: true});
var coord = new google.maps.LatLng(37.423021, -122.083739); // here you created instance of LatLng's class
var marker = new google.maps.Marker({
position: coord, // instead this try:
//position: {lat: 37.423021, lng: -122.083739}, // here is a difference; or try:
//position: new google.maps.LatLng(lat: 37.423021, lng: -122.083739),
map: map
});
}
If it doesn't work check your api key and callback function:
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
Also check css rules: did you set height for your map?
Also I want to explain why I gave two variants of creating properties center and position:
center: {lat: 37.423021, lng: -122.083739}
center: new google.maps.LatLng(lat: 37.423021, lng: -122.083739)
position: {lat: 37.423021, lng: -122.083739}
position: new google.maps.LatLng(lat: 37.423021, lng: -122.083739)
In my practice I used both variants and both works.
Try combinations:
center: {lat: 37.423021, lng: -122.083739} //for var map
position: {lat: 37.423021, lng: -122.083739} //for var marker
center: new google.maps.LatLng(lat: 37.423021, lng: -122.083739) //for var map
position: new google.maps.LatLng(lat: 37.423021, lng: -122.083739) //for var marker
Hope my edited answer help you to find solution. Please, post error message from console if my answer doesn't help. With error message more easier to find solution.
PS. When I need to create Google Map I always use Google Maps APIs examples and it always works.

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