Raja Tamil

Raja Tamil

1661774400

Make A Selected/Clicked Button Active In JavaScript [2022]

Make A Selected/Clicked Button Active In JavaScript

Learn how to make a selected or clicked button active in JavaScript without Loop.

You can either add a CSS class or add one or more CSS propertiesdirectly to a selected button to be active.

Add A Background Colour To A Selected Button

When you want to add some CSS style to a selected/clicked button in JavaScript to make it active,

For Loop will most likely be the first choice in our minds.

But, you do not need to use loop at all.

Let’s see how to do it in action.

Create HTML Button Elements

Here is a simple div tag with an id wrapper.

It has five HTML button elements in it.

Nothing fancy.

<div id="wrapper">
  <button>1</button>
  <button>2</button>
  <button>3</button>
  <button>4</button>
  <button>5</button>
</div>

Attach Click Events To HTML Button Elements

• First, let’s add a click event listener to all the elements inside a div.

const wrapper = document.getElementById("wrapper");

wrapper.addEventListener('click',(e) => {
})

• Check to see if the clicked item is a button inside the click event callback function.

const isButton = e.target.nodeName === 'BUTTON';

• If the clicked item is NOT a button, exit the click event callback function.

So it won’t execute anything further if it’s not a button click.

if (!isButton) {
    return;
}

Add A CSS Property To Clicked Button

Add a background colour to a selected/clicked button by accessing the event object that is passed into the click event callback function.

e.target.style.background = 'red';

This code works fine until the second button is clicked.

By then, both the first and second clicked buttons will have a background colour of red to indicate the active state.

But what we want is to add a background colour to only the currently clicked item and remove it from the previously selected item.

To do that, we need to capture the previously selected/clicked button and remove the background colour from it.

Capture Previously Selected/Clicked Item

• Declare a constant called prevButton outside of the button click event.

• Set its initial value to null.

let prevButton = null;

• Now check to see if any button is added into the prevButton constant.

If it does, remove the background colour by setting its value to none.

if(prevButton !== null) {
   prevButton.style.background = 'none';
}

• Finally, add the currently clicked item to the prevButton.

This way the prevButton does not have any previously clicked button object when a user clicks any of the button for the first time.

And it will become available when a user clicks any button second time onwards.

Continue Reading…

#JavaScript #webdev #webdevelopement #programming #softauthor 

Make A Selected/Clicked Button Active In JavaScript [2022]
Raja Tamil

Raja Tamil

1661169600

Make Pop-Up Modal Window In Vanilla JavaScript [2022]

Make Pop-Up Modal Window In Vanilla JavaScript


Learn how to create a simple responsive pop-up modal window using Vanilla JavaScript along with HTML and CSS with a bit of Flexbox.

Create A Button That Opens Pop Up Modal Window

Declare a <button> HTML element with an id open-modal.

<button id="open-modal">Open Modal Window</button>

The goal is when a user presses this button, the pop-up modal window will open.

Style the button using CSS Flexbox and centre it on the screen.

* {
    margin: 0;
    padding: 0;
    font-family: Arial, Helvetica, sans-serif;
    box-sizing: border-box;
}

body {
    height: 100vh;
    display: flex;
    align-items: center;
    justify-content: center;
}

button {
    padding: 10px;
    font-size: 1.1em;
    background: #32bacf;
    color: white;
    border: none;
    border-radius: 10px;
    border: 1px solid rgba(0, 0, 0, 0.2);
    cursor: pointer;
}

button:hover {
    background: rgba(0, 0, 0, 0.7);
}

Create Pop-Up Modal Overlay

Normally, pop-up modal windows have overlays with a transparent darker background that covers the entire browser screen.

Define a div with an id model-overlay which will cover the entire screen.

<div id="modal-overlay">
<div>

Then, make it to full screen using height:100vh CSS property.

Bring it in front of the button by using position:absolute with a transparent background colour.

#modal-overlay {
    width: 100%;
    height: 100vh;
    position: absolute;
    background: rgba(0, 0, 0, 0.7);
}

I just added the border to see the boundaries of the modal-overlay element.

Center Pop-Up Modal Window To The Modal Overlay

Create a div with an id modal inside the modal-overlay element, which will be an actually pop-up modal window that user interacts with.

<div id="modal-overlay">
  <div id="modal">
  </div>
<div>

Add CSS style to make it visible on the screen.

Adding width:100% and max-width:650px will make sure the width of the pop-up modal window won’t exceed when the browser width is more than 650px.

If the browser width is less than 650px, the pop-up modal window will stretch the width to fill the screen which is normally for mobile viewports.

#modal-overlay #modal {
    max-width: 650px;
    width: 100%;
    background: white;
    height: 400px;
}

Centre the pop-up modal window to the screen using Flexbox.

To do that, just add the three lines of Flexbox code to the modal-overlay which are

  • display:flex → Convert an HTML element to Flexbox
  • align-items:center → centre the pop-up modal window vertically to the viewport
  • justify-content:center → centre the pop-up modal window horizontally to the viewport
#modal-overlay {
   ...
  
   display: flex;
   align-items: center;
   justify-content: center;
}

Open Up Pop-Up Modal Window On Button Click

Now we have the basic pop-up modal window designed using CSS.

Make it visible when a user presses the open modal button.

To do that,

First, hide the modal overlay by default by changing its display property from flex to none.

#modal-overlay {
   ...
  
   display: none; // Changed from flex to none
   align-items: center;
   justify-content: center;
}

Create a DOM reference to the open-modal button as well as the modal-overlay elements.

const openModalButton = document.getElementById("open-modal");
const modalWindowOverlay = document.getElementById("modal-overlay");

Attach a click event to the openModalButton with the callback arrow function showModalWindow.

const showModalWindow = () => {
    modalWindowOverlay.style.display = 'flex';
}

openModalButton.addEventListener("click", showModalWindow);

Set the display property of the modalWindowOverlay to flex inside showModalWindow() function which will open up the modal window.

As you can see, there is no way we can close/hide the pop-up modalwindow after its became visible on the screen.

Let’s fix it!

Close/Hide Pop-Up Modal Window On Button Click

Typically, there will be a close button on the top or bottom right side of the pop-up modal window.

Let’s add a close button on the bottom left side of the modal window.

Define header, content and footer HTML elements inside the pop-up modal window.

<div id="modal">

    <div class="modal-header">
        <h2>Modal Pop Up Window</h2>
    </div>

    <div class="modal-content">
        <p>Modal Content</p>
    </div>
    
    <div class="modal-footer">
        <button id="close-modal">Close</button>
        <button>Save</button>
    </div>

</div>

Generally, you’ll have two buttons on the footer of the pop-up modal window, which may be save and close.

Let’s push the buttons to the bottom using Flexbox.

Turn the display property of the pop-up modal window to flex and set the flex direction to column.

Continue Reading…

#JavaScript #programming #webdev #softauthor 

Make Pop-Up Modal Window In Vanilla JavaScript [2022]
Raja Tamil

Raja Tamil

1660564800

Must-Know e.target in JavaScript Explained [2022]

Must-Know e.target in JavaScript Explained

When you attach an event to an HTML Element, it will return the event object when the event is triggered.

The triggered event could be a click, mouse over, mouse down etc.

The target property of the event object (e) will give the current HTML Element that the event is triggered on.

Let see that in action.

Get Clicked HTML Element Using e.target

Let’s see how to access an HTML Element when the event that it’s attached to is triggered.

  1. Create an HTML Element
  2. Attach an Event to it
  3. Trigger an event
  4. Capture the returned event object inside the event callback function
  5. Get the current HTML Element by accessing the target property of the event object

1. Define an HTML Button Element

<button id="button">Button</button>

Create a DOM reference to the button element using its ID attribute.

const button = document.getElementById('button');

2. Attach an event to the button element by calling addEventListener() method on the button object.

button.addEventListener();

The addEventListener() takes two main arguments which are:

  • click → the event name
  • buttonPressed → the callback function which will be invoked when the click event is triggered
button.addEventListener("click", buttonPressed);

Declare the callback function buttonPressed().

const buttonPressed = () => {
  console.log("I'll be called every time when a button is pressed")
}

3. The buttonPressed() function will be called every time the click event is triggered on the button.

Capture / Get Clicked Element Inside The Callback Function

Every time a user presses the button, it will return an HTML Element as an event object.

4. The returned event object will be passed into the buttonPressed()callback function as a parameter called e.

const buttonPressed = (e) => {
  console.log(e); //short form of event
}

5. Use the target property of the event object to get the currently clicked HTML Element, which is button in this case.

const buttonPressed = (e) => {
  console.log(e.target); //<button id="open-modal">Open Modal Window</button>
}

Get Clicked Child Element Using e.target

Learn how to get the child element using e.target when a parent element of the event is triggered.

The sample wrapper div with an id button-group has four button elements inside.

<div id="button-group">
   <button>Button 1</button>
   <button>Button 2</button>
   <button>Button 3</button>
   <button>Button 4</button>
</div>

Attach a click event to the wrapper div instead of each button.

const buttonGroup = document.getElementById("button-group");

const buttonGroupPressed = (e) => {
    console.log(e.target); // Get any clicked element inside button-group wrapper div
}

buttonGroup.addEventListener('click', buttonGroupPressed);

e.target will return any currently clicked HTML element, which can be either the parent (#button-group) or child elements (buttons inside).

The parent element will be referred to an element that has a click event attached to it.

 

Continue Reading …

#JavaScript #programming #webdevelopment  #softauthor 

Must-Know e.target in JavaScript Explained [2022]
Raja Tamil

Raja Tamil

1659960000

Firebase V9 Firestore UPDATE Document Data Using updateDoc()

Firebase V9 Firestore UPDATE Document Data Using updateDoc()

There are two methods you can use to update an existing document in Firebase Version 9 Cloud Firestore.

setDoc() 
updateDoc() you’re here

Using updateDoc(), you can only update the document field of an existing document in the Firestore Database which can be:

Add A New Document Field Using updateDoc()

Here is a sample document inside the cities collection from the Cloud Firestore Database.

In order to update an existing document using the updateDoc()method, we need three methods:

  • getDatabase() → where we want to update a document.
  • doc() → where we’ll be passing references of database, collection and ID of a document that we want to update one its fields.
  • updateDoc() → where we actually pass new data that we want to replace along with the doc() method.

Import Firestore Database and de-structure the three methods we need:

import { getFirestore, doc, updateDoc } from "firebase/firestore";

Initialize Firestore Database and store it in a constant called db.

const db = getFirestore();

The updateDoc() method takes two arguments which are:

  • doc() – Where we pass database, collection and document ID references
  • data {} – Where we pass the actual data that we want to update into an existing document

Doc() Method

The first argument of the updateDoc() method is the doc() method.

This doc() method takes three arguments.

  • database → db
  • collection name → cities
  • document ID → yftq9RGp4jWNSyBZ1D6L (ID of a document – see screenshot above)

Call the doc() method and pass database references (db), collection name (cities) and document ID (yftq9RGp4jWNSyBZ1D6L).

Assign it to a constant called docRef.

const docRef = doc(db, "cities", "yftq9RGp4jWNSyBZ1D6L");

Document Data {}

The second argument of the updateDoc() method is the actual data that we want to update an existing document entirely inside the cities collection.

Let’s say I want to add a new document field called code with a value of 613.

Declare a constant called data and assign a JavaScript object with the one property that we want to add to the existing document.

In this case, code.

const data = {
  code: "613"
};

Make An updateDoc() Query

Now that we have both arguments we need to perform updateDoc()query to update an existing document by adding a new document field.

import { getFirestore, doc, updateDoc } from "firebase/firestore";

// Your Firebase SDK Initialization code here

const db = getFirestore(); // initialize Firestore

const docRef = doc(db, "cities", "yftq9RGp4jWNSyBZ1D6L");

const data = {
  code: "613"
};

updateDoc(docRef, data)
.then(docRef => {
    console.log("A New Document Field has been added to an existing document");
})
.catch(error => {
    console.log(error);
})

Update A Value Of Document Field Using updateDoc()

You can also update an existing document field with a new value.

Let’s change the value of Ontario to ON in the province field.

Continue Reading…

#firebase #JavaScript #softauthor #programming 

Firebase V9 Firestore UPDATE Document Data Using updateDoc()
Raja Tamil

Raja Tamil

1659355200

Firebase V9 Firestore Add Data Using setDoc() [2022]

Firebase V9 Firestore Add Data Using setDoc()

There are two methods that we can use to add document data to the Firebase Version 9 Cloud Firestore.

Note: Before going further, you’ll need to do three things:

  1. Create A Firebase Project from Firebase Console
  2. Register an app for Web (JavaScript)
  3. Add Firebase SDK to JavaScript Web app

Using the setDoc() method, you can add a document to the Firestore database by creating:

Add Data Using setDoc() With Auto-ID

In order to use the setDoc() method, we need to import three methods from the Firebase Firestore Import Statement.

import { getFirestore, collection, setDoc } from "firebase/firestore";
  1. getDatabase() → Firestore database where we want to add data as a document.
  2. collection() → Where we want to add collection name and database references.
  3. setDoc() → Where we actually pass our data along with thecollection name and db references.

Initialize Firestore database:

const db = getFirestore(app);

Collection() Method

The first argument of setDoc() method is the collection() method

This collection() method also takes two arguments.

  • database → db
  • collection name → users

Invoke the collection() method and pass database references (db) and collection name (countries) in quotes to it.

Assign it to a constant called dbRef.

const dbRef = collection(db, "countries");

Document Data {}

The second argument of the setDoc() method is the actual data that we want to store as a document inside the countries collection.

The good news is that we can simply store a JavaScript object as document data inside the Firestore Database.

So let’s create a JavaScript object with a couple of key-value pairs, aka properties.

const data = {
   name: "Ottawa",
   country: "Canada",
   province: "ON"
};

Make A setDoc() Query

Now we have both arguments we need in order to use setDoc() method successfully.

Let’s call the setDoc() method and pass dbRef and data as arguments to it.

import { getFirestore, collection, setDoc } from "firebase/firestore";

// Your Firebase SDK Initialization code here

const db = getFirestore(app);

setDoc(dbRef, data)
.then(docRef => {
    console.log("Document has been added successfully);
})
.catch(error => {
    console.log(error);
})

Run the setDoc() query…

And you can see a brand new document has been created inside the countries collection with an auto-generated document ID.

Add Data Using setDoc() With Custom-ID

With the setDoc() method, we can create our own custom document ID when adding data to Firestore database.

Instead of using the collection() method, we need to use the doc()method.

import { getFirestore, doc, setDoc } from "firebase/firestore";
  1. getDatabase()Firestore database where we want to add data as a document.
  2. doc() → Where we want to add collection name and database references as well as our custom document ID.
  3. setDoc() → Where we actually pass our data along with the collection name and db references.

Doc() Method

The first argument of the setDoc() method when creating a custom document ID will be doc() method.

This doc() method takes three arguments.

  • database → db
  • collection name → countries
  • custom document ID → my.custom.id@gmail.com (this could be anything you would like)

Continue Reading…

#firebase #JavaScript #softauthor 

Firebase V9 Firestore Add Data Using setDoc() [2022]
Raja Tamil

Raja Tamil

1658750400

Firebase 9 Firestore GET ALL DOCUMENTS Data From A Collection

Firebase 9 Firestore GET ALL DOCUMENTS Data From A Collection

Learn how to get all the documents data from a collection in Firebase version 9 Cloud Firestore Database using the getDocs() method.

The Firestore Database has a cities collection that has four documents in it like the screenshot below.

Import Firestore Database and de-structure three methods that are:

  • getFirestore() → Firestore Database
  • doc() → It takes references of database and collection that we need to get the data from.
  • getDocs() → It gets data from collection based references mentioned in the doc() method.
import { getFirestore, doc, getDocs } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";

The import statement uses the CDN version of the Firebase SDK in this example.

Initialize Firestore Database

const db = getFirestore();

The getDocs() method takes a single argument which is the doc()method.

Two of the arguments of doc() method

  • Database → db
  • Collection name → cities in this case (see the screenshot above)

Call the doc() method and pass two arguments and assign it to a constant called colRef (short form for collection reference).

const colRef = collection(db, "cities");

Invoke the getDocs() method passing colRef as an argument to it.

The getDocs() method will return a promise, and add await keyword in front of it.

Assign it to a constant called docsSnap (short form for documents snapshot).

const docsSnap = await getDocs(colRef);

To see each document from the cities collection, loop through the docsSnap object using the forEach() method.

docsSnap.forEach(doc => {
    console.log(doc.data());
})

The forEach() method takes a function as an argument with the parameter called doc.

Note: The parameter doc has nothing to do with the doc() method mentioned above.

The doc parameter will get a document from docsSnap on each iteration.

To get the actual document data, call the data() method on the docobject.

To get the id of a document, access the id property on the doc object.

Continue Reading… 

#firebase #JavaScript #softauthor 

Firebase 9 Firestore GET ALL DOCUMENTS Data From A Collection
Raja Tamil

Raja Tamil

1658145600

Firebase 9 Firestore Get A Document By ID Using getDoc() [2022]

Firebase 9 Firestore Get A Document By ID Using getDoc()

Learn how to get document by ID using the getDoc() method in Firebase version 9 Cloud Firestore Database.

The sample Firestore Database has a cities collection that has four documents in it like in the screenshot below.

Let’s get the first document of the cities collection by id.

In this case: Edmonton document using its ID (2l3bcSGs2vZBIc3RODwp)

Import Firestore Database and de-structure the three methods that we need:

  • getFirestore()Firestore Database
  • doc() → It takes references of database, collection name and ID of a document as arguments
  • getDoc() → getDoc() query gets data of a specific documentfrom collection based references mentioned in the doc()method.
import { getFirestore, doc, getDoc } from https://www.gstatic.com/firebasejs/9.8.4/firebase-firestore.js";

The import statement uses the CDN version of the Firebase SDK in this example.

Initialize Firestore Database

const db = getFirestore();

The getDoc() method takes a single argument which is the doc()method.

The three arguments of the doc() method are:

  • Database → db
  • Collection name → cities in this case (see the screenshot above)
  • ID of a document → 2l3bcSGs2vZBIc3RODwp in this case (see the screenshot above)

Call the doc() method, pass three arguments and assign it to a constant called docRef (short form for document reference).

const docRef = doc(db, "cities", "2l3bcSGs2vZBIc3RODwp");

Invoke the getDoc() method passing docRef as an argument to it.

The getDoc() method will return a promise, add await keyword in front of it.

Continue Reading…

#JavaScript #firebase #softauthor 

Firebase 9 Firestore Get A Document By ID Using getDoc() [2022]
Raja Tamil

Raja Tamil

1657540800

Firebase V9 Firestore Update Document Data Using setDoc() [2022]

Firebase V9 Firestore Update Document Data Using setDoc()

There are two methods you can use to update an existing document in Firebase Version 9 Cloud Firestore.

Note: Before going any further, you’ll need to do three things:

  1. Create A Firebase Project from Firebase Console
  2. Register an app for Web (JavaScript)
  3. Add Firebase SDK to JavaScript Web App

Using the setDoc() method, you can update

In addition to that, you can also add a brand new document to a collection using setDoc() method.

Firestore Update Entire Document

Here is the sample data stored in the Cloud Firestore.

Let’s update an entire document using the setDoc() method.

In order to update data entirely using the setDoc() method, we need three methods.

  • getDatabase() → where we want to update a document.
  • doc() → where we’ll be passing references of database, collection and ID of a document that we want to update.
  • setDoc() → where we actually pass new data that we want to replace along with the doc() method.

Import Firestore Database and de-structure the three methods we need:

import { getFirestore, doc, setDoc } from "firebase/firestore";

Initialize Firestore Database:

const db = getFirestore(app);

Doc() Method

The first argument of the setDoc() method is the doc() method.

This doc() method takes three arguments.

  • database → db
  • collection name → cities
  • document ID → p4eZc05QV43InigxALJ (ID of a document – see screenshot above)

Call the doc() method and pass database references (db), collection name (cities) and document ID (p4eZc05QV43InigxALJ).

Assign it to a constant called docRef.

const docRef = doc(db, "cities", "p4eZc05QV43InigxALJ");

Document Data {}

The second argument of the setDoc() method is the actual data that we want to update an existing document entirely inside the citiescollection.

As you can see the new data has complete different than the existing document data in the Firestore database including the field name.

const data = {
  title: "Vancouver",
  provinceName: "British Columbia",
  countryCode: "CA"
};

SetDoc() Query To Update A Document

Now we have both arguments we need in order to use setDoc()method successfully.

Let’s call the setDoc() method and pass docRef and data as arguments to it.

Continue Reading…

#firebase #JavaScript #softauthor 
 

Firebase V9 Firestore Update Document Data Using setDoc() [2022]
Raja Tamil

Raja Tamil

1656936000

Firebase V9 Firestore Add Document Data Using addDoc() [2022]

There are two methods that we can use to add document data to the Firebase Version 9 Cloud Firestore.

Note: Before going further, you’ll need to do three things:

  1. Create A Firebase Project from Firebase Console
  2. Register an app for Web (JavaScript)
  3. Add Firebase SDK to JavaScript Web app

In order to use the addDoc() method, we need to import three methods from the Firebase Firestore import statement.

  1. getDatabase() → Firestore database where we want to add data as a document.
  2. collection() → Where we want to add collection name and database references.
  3. addDoc() → Where we actually pass our data along with the collection name and db references.
import { getFirestore, collection, addDoc } from "firebase/firestore";

1. Initialize Firestore Database

Initialize Firestore database and store it in constant called db

const db = getFirestore(app);

The addDoc() method will take two arguments:

  • collection() – pass database and collection name references as arguments to it.
  • data {} – data that we want to add to a collection as one of its documents.

2. Collection() Method

This collection() method also takes two arguments.

  • databasedb
  • collection nameusers

Invoke the collection() method and pass database references (db) and collection name (users) in quotes to it.

Assign it to a constant called dbRef.

const dbRef = collection(db, "users");

As you can see, Firestore Database does not have the collection name “users

You may wonder…

How can we add data to a collection that does not exist in the Firestore Database?

In the Firestore Database, you can only add one or more documents inside a collection.

But you won’t be able to add the collection itself without any document.

When you add data as document to a collection, the addDoc()method will try to find the collection name specified in the collection() method.

In this case users.

If it’s unable to find the collection name users,

It will create a new collection called users and add the data inside it as a document.

3. Document Data {}

The second argument of the addDoc() method is the actual datathat we want to store as a document inside the users collection.

The good news is that we can simply store a JavaScript object as document data inside the Firestore database.

So let’s create a JavaScript object with a couple of key-value pairsaka properties.

const data = {
   name: "Raja Tamil",
   country: "Canada"
};

4. Add Document Data Using addDoc()

Now we have both arguments we need in order to use addDoc()method successfully.

Continue Reading…

#firebase #JavaScript #softauthor 

Firebase V9 Firestore Add Document Data Using addDoc() [2022]
Raja Tamil

Raja Tamil

1656331200

Add Firebase SDK V9 to JavaScript Web App In Minutes [2022]

Add Firebase SDK V9 to JavaScript Web App In Minutes [2022]

In this Firebase version 9 tutorial, you’re going to learn how to add Firebase to your JavaScript web apps which will be the very first step that you need to get started with Firebase.

In order to use Firebase V9 on your web app, you’ll need to:

  1. Create A Firebase Project
  2. Register App for web
  3. Add Firebase SDK 9 to JavaScript web app

1. Create A Firebase Project From Firebase Console

  • Go to the Firebase ConsoleGo to console or Sign in button at the top right.
  • Log in with Gmail account.

  • Once you’re logged in, click the Add Project button to create a brand new Firebase project.

  • Give it a project name of your choice and click continue.

  • Turn off Enable Google Analytics for this Project and click Create Project.

  • It will take a few seconds to complete the creating a project process.

  • Click continue and it’ll take you to the Firebase Project Dashboard.

2. Register App

The Firebase Project Dashboard offers to register an app for five different platforms:

  • iOS
  • Android
  • Web
  • Unit, and
  • Flutter

Let’s Register an app for Web (JavaScript).

Continue Reading…

#firebase #JavaScript #softauthor 

Add Firebase SDK V9 to JavaScript Web App In Minutes  [2022]
Raja Tamil

Raja Tamil

1655726400

Google Maps API Geocode Explained [2022]

By the end of this tutorial, you’ll have a better understanding of how to use Google Maps Geocoding API using its HTTP Interface as well as JavaScript SDK.

Google Geocoding API

Geocoding API is one of the many services that Google Maps API eco-system offers.

Geocoding is a process of converting a human readable physical address into geographic coordinates (latitude and longitude values).

One of the very common uses is when you want to show a business location on the Google Maps on the website.

In order to use Geocoding API, you’ll need to do two things:

Enable Geocoding API

In your Google Cloud Platform Console, go to APIs & Services Dashboard → Enable APIs & Services at the top and choose Maps JavaScript API from the API Library.

This will open up the Maps JavaScript API page and Enable it.

Then, scroll down to “More solutions to explore” and choose Geocoding API Enable it.

Convert Address To Latitude & Longitude

Let’s convert an actual street address into geographical coordinates in the form of latitude and longitude which is called Geocoding as I mentioned earlier.

Sometimes, you may get a CORS error and you can fix it by appending the proxy server URL such as heroku.

const address = "111 Wellington St, Ottawa, ON K1A 0A9, Canada";

fetch(`https://maps.googleapis.com/maps/api/geocode/json?address=${address}&key=[YOUR_API_KEY]`)
.then((response) => {
    return response.json();
}).then(jsonData => {
    console.log(jsonData.results[0].geometry.location); // {lat: 45.425152, lng: -75.6998028}
})
.catch(error => {
    console.log(error);
})

Once you’ve access to latitude and longitude values, you can Create a Google Maps object and Place/Position the address on the map using Marker.

Convert Address To Latitude & Longitude

Let’s see how to convert Latitude and Longitude values to a street address. This process is called Reverse Geocoding.

const latLng = "45.425507, -75.700233";

fetch(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${latLng}&key=[YOUR_API_KEY]`)

.then((responseText) => {
    return responseText.json();
})
.then(jsonData => {
    console.log(jsonData.results[0].formatted_address); //111 Wellington St, Ottawa, ON K1A 0A9, Canada
})
.catch(error => {
    console.log(error);

})

This is a great option when you want to detect a user’s current location from a browser and convert it into a street address.

Geocoder Using JavaScript SDK

You can also use Google Maps Geocoding API service via its JavaScript SDK using Geocoder instead of using the API URL directly.

To do that, add the JavaScript SDK CDN to your index.html file.

Make sure to add your own API Key.

<script src="https://maps.googleapis.com/maps/api/js?key=[YOUR_API_KEY]&callback=initialize" async defer></script>

As soon as the JavaScript SDK is loaded into the browser, the initialize function will be called.

Inside the initialize function, convert the street address to latitude and longitude values using the Geocoder object.

Continue Reading…

#JavaScript #googlemaps #softauthor 

 

Google Maps API Geocode Explained [2022]
Raja Tamil

Raja Tamil

1655122029

Filter() vs Find() Using JavaScript Array Explained!

The filter() function will get all the elements from an array as long as the provided condition is met.

It’ll return a new array just with filtered elements.

The find() function will get only the very first element as soon as the provided condition is met and ignores everything else. It’ll return just that element.

That’s simple eh!

Let’s see that in action

Filter()

When we loop through a JavaScript array using filter() function.

It’ll search and get all the elements that meet a specific condition in that array.

Then, it will return them as a new array.

And the output will be [20, 25].

const ages = [3, 10, 18, 20, 25];

const foundItems = ages.filter(age => {
  return age > 18;
});

console.log(foundItems); // [20, 25]

Find()

On the other hand, find() function will only return the very first element that meets the provided condition and ignores everything else from a JavaScript array.

And the output will be 20.

const ages = [3, 10, 18, 20, 25];

const found = ages.find(age => {
  return age > 18;
});

console.log(found); // 20

Recommended

#JavaScript #googlemaps #programming #softauthor 

Filter() vs Find() Using JavaScript Array Explained!
Raja Tamil

Raja Tamil

1654516800

Find() An Element From JavaScript Array Explained!

What is find() Method?

The find() method can only be invoked on a Javascript array.

const ages = [3, 10, 18, 20, 25];
ages.find();

It’s one of the higher order functions similar to map, reduce, filter etc.

Any function that accepts or return another function called higher-order functions.

Apparently find() will only take a function as an argument that is required.

How Does Find() Method Work?

The find() method will search the very first element from a given Javascript array

Until the condition we specify is met or satisfied.

Then..

It will exit & ignore everything else

Including the second element that meets the condition.

Find() Method In Action

First, invoke the find() method in the ages javascript array.

Which will loop though the the array.

const ages = [3, 10, 18, 20, 25];
ages.find();

To capture each element on each iteration

We need to pass an arrow function as an argument with the parameter called age to the find() method

const ages = [3, 10, 18, 20, 25];
ages.find(age => {
});

The parameter age will have an element from an array on each iteration.

Finally, add the condition inside the arrow function

Let’s say I want to find the first element which is over 18 in the ages array.

const ages = [3, 10, 18, 20, 25];
ages.find(age => {
  return age > 18;
});

This will get the very first element of the ages array as soon as it finds any number that is above 18.

In this case, there is 20 which is 4th index.

And exit the loop and it won’t go any further.

You can assign the value that the find() method returns into a variable called found like below.

const ages = [3, 10, 18, 20, 25];
const found = ages.find(age => {
  return age > 18;
});

console.log(found); // 20

You can make it short like this

const ages = [3, 10, 18, 20, 25];
const found = ages.find(age => age > 18);

console.log(found); // 20

Find An Element From Array of Objects

If you’ve array of objects, you can literally find any object by the value of one of its properties.

Let’s say you want to find the very first object that has an age is over 18, you can do something like the code below.

const users = [
  {name: "Pagalavan", age: 3},
  {name: "Ellalan", age: 10},
  {name: "Vanagamudi", age: 18},
  {name: "kittu", age: 20},
  {name: "amuthan", age: 25}
];

const found = users.find((user) => {
     return user.age > 18;
});

console.log(found); // { age: 20, name: "kittu" 

Similarly, you can also search for a specific user object by its name property value.

const found = users.find((user) => {
     return user.name === "amuthan";
});

console.log(found); // { age: 25, name: "amuthan" }

Find() returns Undefined

If the find() method is unable to find an element that meets the provided condition, it’ll return undefined.

As you can see, I’m trying to find an age which is above 35

Apparently, none of the elements in the ages array matches that.

const ages = [3, 10, 18, 20, 25];

const found = ages.find(age => 
    age > 35
); // undefined

if(found) {
  //do something
}

Which obviously return undefined.

Undefined often seen as bad or error by novice developers but it’s not.

In fact, undefined is one of the data types similar to Number, Boolean, Null etc.

This will be a great scenario if you want to check if a specific value or element exists in a JavaScript array.

Find A Specific Array Index Using findIndex()

If you want to get an index of an element that satisfies the provided condition, you might want to consider using findIndex().

The findIndex() is very similar to find() method but it will return the index value of the element that meets the provided condition instead of the actual element.

You can do something like this.

const ages = [3, 10, 18, 20, 25];

const foundIndex = ages.findIndex((age) => 
    age > 18
);

console.log(foundIndex); // 3

If you want to get the element using its index value from array, you can easily do something like this:

Continue Reading…

#javascipt #softauthor #programming 

Find() An Element From JavaScript Array Explained!