Sung Kim Sung Kim - 1 year ago 26
Javascript Question

passing LatLng variable from another function to google maps initialize

I have a firebase database where i can retrieve latitude and longitude value and wrap that up as var coords.

function getCoords() {
var place_data= firebase.database().ref("/place/name");

place_data.once('value').then(function(snapshot) {

var longitude = snapshot.child("Event_long").val();
var latitude = snapshot.child("Event_lat").val();
var coords = new google.maps.LatLng(latitude, longitude);
alert(coords); //i get (43.6672568, -79.4000838) as alert//
});
}


this is google maps initialization.

function initializeMap() {
var iconBase = {url:'/images/wing.pin.png'};


var map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: coords,
mapTypeId: 'satellite'
});

marker = new google.maps.Marker({
icon: iconBase,
map: map,
draggable: true,
animation: google.maps.Animation.DROP,
position: coords
});
marker.addListener('click', toggleBounce);
}


i just need function initializeMap to read var 'coords'. i've tried putting 'coords' as globalvariable, tried to enclose getCoords function inside other function. They just don't seem to read. Any efficient way to do this?

Answer Source

Functions must be called.

Modify your function to return the lat/long to the caller...

function getCoords() {
    var place_data= firebase.database().ref("/place/name");

    place_data.once('value').then(function(snapshot) {

    var longitude = snapshot.child("Event_long").val();
    var latitude = snapshot.child("Event_lat").val();
    return new google.maps.LatLng(latitude, longitude); //modified this line
});
}

And call it here...

function initializeMap() {
 var iconBase = {url:'/images/wing.pin.png'};
 var coords = getCoords(); // called here

 var map = new google.maps.Map(document.getElementById('map'), {
 zoom: 15,
 center: coords,
 mapTypeId: 'satellite'
 });

 marker = new google.maps.Marker({
 icon: iconBase,
 map: map,
 draggable: true,
 animation: google.maps.Animation.DROP,
 position: coords
 });
 marker.addListener('click', toggleBounce);
 }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download