transferring a LatLng variable from one function to initialize Google Maps

I have a database in firebase that stores latitude and longitude values which I retrieve as the variable 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);  //after running this code, I get (43.6672568, -79.4000838) displayed in an alert message//
});
}

This code is for initializing Google Maps.

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 am struggling to make the function initializeMap read the variable 'coords'. I've attempted making 'coords' a global variable and enclosing the getCoords function within another function, but they don't seem to work. Is there a more efficient way to achieve this?

Answer №1

Make sure to invoke functions.

Adjust your function so it can provide the latitude and longitude 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); //updated this line
});
}

Now, call the function in this section...

function initializeMap() {
 var iconBase = {url:'/images/wing.pin.png'};
 var coords = getCoords(); // invoking 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);
 }

Answer №2

I managed to achieve my goal by passing latitude and longitude as parameters in the initializeMap function like this:

function fetchCoordinates() {
var placeData = firebase.database().ref("/place/name");

placeData.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);

 initializeMap(latitude, longitude);
 });

 }


  //Display Map in Summary Tab//
  function initializeMap(latitude,longitude) {
  var iconBase = {url:'/images/wing.pin.png'};


  var map = new google.maps.Map(document.getElementById('map'), {
  zoom: 17,
  center:  new google.maps.LatLng(latitude, longitude),
  mapTypeId: 'roadmap'
  });

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Vue.js component mismatch in the layout

Attempting to set up a Vue application with vuetify while incorporating layouts. As a newcomer to Vue, I may have made some beginner errors. Here is the structure of my app: main.js // The Vue build version to load with the `import` command // (runtime- ...

The output of JSON.stringify() when given a single value as input

The JSON.stringify() function is designed to convert a JavaScript value into JSON format. console.log(JSON.stringify('a')); //output: "a" console.log(JSON.stringify(1)); //output: 1 console.log(JSON.stringify(true)); //output: true However, tec ...

What is the optimal method for transmitting data for a substantially large music playlist via HTTP?

I am currently in the process of developing an online music player. My main challenge lies in retrieving a comprehensive list of songs from the database and transmitting it to the user. The user should have the ability to create playlists on-the-go, hence ...

Verifying the presence of a value within an SQL table

I am currently working on developing a bot that requires me to save the commandname and commandreply in a database. Right now, I am using mySQL Workbench for this task. My goal is to verify if the commandname provided by the user already exists in the tab ...

Node.JS has deceived us with its false promises of `import` support

Could it be that I am making a mistake? I have been eagerly awaiting the experimental ES6 module loader in Node.JS since version 10. This feature is crucial for me to seamlessly use the same code in both the browser and node environments. This is how I w ...

angularjs select not chosen option

Hey there, I'm currently attempting to select an item from an array in the select options by using a string value. Below is my HTML code: <!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularj ...

Getting the value of an element using a string in JQuery

How can I achieve the following using JQuery? var test = "'#ISP'"; alert($(test).val()); I am receiving a "Syntax error, unrecognized expression." I believe I might be overlooking something here. Thank you in advance! ...

Unable to retrieve Vuex state within a function

Currently, I am developing a Laravel+Vue application where Vuex is used for state management. While working on form validation, everything seems to be progressing smoothly except for one particular issue that has me stuck. The problem arises when I attempt ...

What is the best way to show a message within a specific HTML division with JavaScript?

Here's my attempt at solving the issue: <head> <script> function validateForm() { var username = document.forms["login"]["uname"].value; var password = document.forms["login"]["pwd"].value; if (username == "" || p ...

Struggling to make jQuery code function properly in Wordpress, despite attempting to use noConflict

I have created a custom image grid gallery in WordPress using HTML and CSS, complete with popups and sliders. I had to code it myself because I couldn't find a suitable plugin that matched my design preferences. I have tested the functionality on my ...

Steps to hide a div after it has been displayed once during a user's session

After a successful login, I have a div that displays a success message and then hides after 4 seconds using the following JavaScript code: document.getElementById('success').style.display = 'none'; }, 4000); While this functionality wo ...

Transforming the jQuery tooltip to be shown in a column layout

Hello, I am currently using the displayTag library to showcase some tables. My goal is to include a tooltip on each display:column element by utilizing jQuery. Below is the code snippet in question: <c:set var="titleName"><wp:i18n key="FILENAME" ...

Bidirectional binding with complex objects

In my Angular2 app, I have a class called MyClass with the following structure: export class MyClass { name: Object; } The name object is used to load the current language dynamically. Currently, for two-way binding, I am initializing it like this: it ...

Value as a String inside an Object

I am encountering an issue with using the obj to store string values in my project. The strings contain commas, and for some reason, it is not working as expected. const resizedUrl ={ 'mobile': "'images','400x/images' ...

Experiencing a hiccup in React while attempting to play an mp3 file

My project includes the following code snippet, with an example mp3 file and npm package: https://www.npmjs.com/package/react-sound import React from 'react'; import Sound from 'react-sound'; class CustomSound extends React.Component ...

Attempt to retrieve JSON-formatted data from a repository on Git

As a novice, I am delving into the world of ajax and experimenting with json files. Utilizing JSON formatted data is something I am keen on mastering. However, my request seems to be yielding an empty outcome. An Update: Below is the piece of code I am wor ...

AngularJS - Determine the correct condition or make a choice from the available options

I'm having trouble figuring out how to save the option I select to a viewmodel. The ng-model should save whatever option I choose, and if nothing is selected, the value should default to "Select One." The available options are YES (true) / NO (false). ...

What is the way to utilize a scope variable within an ng-repeat filter?

I'm feeling a bit lost trying to navigate through this task with AngularJS. As a newbie to the framework, I'm struggling to find out how to achieve what I need. I have a group of users that I am looping through by using ng-repeat, but I can' ...

What is the best way to access the rendered child components within a parent component?

I am seeking a way to retrieve only the visible child components within a parent component. Below is my unsuccessful pseudo-code attempt: parent.component.html <parent (click)="changeVisibility()"> <child *ngIf="visible1"></child> ...

Sending JSON data from an iOS app to a Flask backend

Within my Flask Python web application, I store certain parameters in SessionStorage to later send back to Flask and save this data as a text file. Interestingly, the process functions perfectly on PCs and Android devices but encounters issues on iOS devi ...