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

Leveraging jQuery Ajax and MySQL to generate dynamic HTML content

I'm in the process of creating a unique photo gallery that utilizes dynamic features. Instead of relying on constant HTML/PHP refreshing for updates, I am incorporating jQuery to handle dynamic MYSQL queries. As a beginner, I've managed to creat ...

Looking to add elements to a specific div dynamically using jQuery? Let's explore how to insert comments seamlessly

I would like to implement a comment system that adds entered comments to a specific div. Here's the code I have so far: <ul class="comments"> <li> <a class="commenter_name" href="/">Dushyanth Lion</a> ...

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...

Utilizing a custom function declared within the component to handle changes in Angular's ngOnChanges

Although it may seem like a simple question, I'm struggling to find a solution. Here's the issue at hand: In my Angular Component, there's a function that I need help with. export class RolesListComponent implements OnInit, OnChanges { ...

Exploring the inner workings of AngularJS SEO in HTML5 mode: Seeking a deeper understanding of this hidden functionality

There are plenty of resources available for incorporating SEO-friendly AngularJS applications, but despite going through them multiple times, I still have some confusion, especially regarding the difference between hashbang and HTML5 mode: In hashbang (# ...

How can the CORS issue be resolved when sending a form from a client to an AWS API gateway function?

Within my front end React application, I am looking to implement a contact form that will submit data to a Lambda function via an API Gateway with a custom domain attached. The frontend operates on the domain dev.example.com:3000, while the API Gateway is ...

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

Tips for effectively engaging with a Component's aggregationUnleash the full potential of

After configuring an aggregation for my Component, here is what it looks like: aggregations : { busyDialog : { type: "sap.m.BusyDialog", multiple: false } } The aggregation is named ...

Sharing an array with a child component using the @Input decorator

I am attempting to send an array to a child component. The array is created within the subscribe method of the onInit lifecycle hook in the parent component. Parent component: import { Component, OnInit } from '@angular/core'; @Component({ s ...

The request made to `http://localhost:3000/auth/signin` returned a 404 error, indicating that

My goal is to access the signin.js file using the path http://localhost:3000/auth/signin Below is my code from [...nextauth].js file: import NextAuth from "next-auth" import Provider from "next-auth/providers/google" export default N ...

Error in JavaScript: Uncaught TypeError - Unable to access the "left" property of an undefined object

This error is really frustrating and I've come across several inquiries regarding this console issue. It's not providing enough information in the chrome console for me to effectively troubleshoot. /** * Adjustment of dropdown menu positio ...

Accessing data from a live database in a randomized sequence

When retrieving items from a database, there is often a common code pattern that looks like this: const [dataRcdArray, setDataRcdArray] = useState<never[]>([]); ..... snapshot.forEach((child:IteratedDataSnapshot) => { setDataRcdArray(arr ...

Adjust the fixed navbar position in MaterializeCSS as you scroll

First of all, I apologize for my limited proficiency in English. I have a website with a company logo at the top and a navigation bar below it. My goal is to change the position of the navigation bar to the top when scrolling past the company logo. I att ...

Bizarre JavaScript Comparisons

I encountered an issue with the comparison process. The expected result should be 11 since the cost of the product at index 11 is lower than the cost of the product at index 18. However, the computed result turns out to be 18. var scores = [60, 50, 6 ...

I need to figure out a way to validate form data dynamically as the number of fields constantly changes. My form data is being sent via Ajax

Click validation is desired. It is requested that before transmitting data, the validate function should be executed. If there is an empty field, a message should be displayed and the data should not be sent to the PHP file. In case there are no empty fi ...

An unexpected error has occurred in the browser console: The character '@' is not valid

I recently made the decision to dive into learning about Unit Testing with JavaScript. To aid in this process, I started using both Mocha.js and Chai.js frameworks. I downloaded the latest versions of these frameworks onto my index.html from cdnjs.com. How ...

Leveraging the power of jQuery Validation in conjunction with Bootbox

I am currently facing an issue with integrating the jQuery validation plugin with bootbox.js (modals). The modal contains a form with fields that require validation. To showcase my problem, I have set up a jsFiddle here: http://jsfiddle.net/rDE2q/ Upon ...

Differences between Array `forEach` and `map()`

I am having trouble displaying the options list even though I am passing an array. Any assistance would be greatly appreciated. Thank you. const options_A = [ { label: "AA", value: "AA" }, { label: "BB", valu ...

Tips for extracting only the filename from chokidar instead of the entire file path

I am trying to capture the filename that has been changed, removed, or renamed, but I am currently receiving the full file path. Question: How can I extract only the filename when it is changed, instead of working with the entire file path? This is what ...

Achieving the Menu Hover Effect - step by step guide to recreating this stylish effect

I recently came across a stunning hover effect on the main menu of a website (red rectangles above menu). It's quite impressive! I found it here: Now, I want to incorporate this same effect into my own website. Unfortunately, there doesn't seem ...