IP GEO Location

FREEMIUM
By FutureAPI | Updated a month ago | Location
Popularity

9.4 / 10

Latency

86ms

Service Level

100%

Health Check

N/A

Back to All Tutorials (1)

Displaying Geographical Coordinates on a Website Using JavaScript and Google Maps API

Certainly! Hereโ€™s a tutorial on how to display obtained geographical coordinates on a website using JavaScript and the Google Maps API:

Step 1: Obtain an API Key

Before you begin, youโ€™ll need to get a Google Maps API key to use Google Maps services. You can do this by registering your project on the Google Developer Console and creating an API key.

  1. Go to the Google Developer Console and sign in to your account or create a new one if you donโ€™t have it.
  2. Choose your project or create a new one.
  3. Enable the โ€œMaps JavaScript APIโ€ service for your project.
  4. Obtain an API key and ensure itโ€™s kept secure.

Step 2: Website HTML and JavaScript Part

Create a new folder in your project and upload the following files:

index.html


<!DOCTYPE html>
<html>
<head>
  <title>Geolocation on Google Maps</title>
  <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
  async defer></script>
</head>
<body>
  <div id="map" style="height: 400px;"></div>
  <script src="script.js"></script>
</body>
</html>

script.js


// Initialize the map
function initMap() {
  // Obtained coordinates
  var latitude = 42.36; // Example: Enter your latitude coordinates
  var longitude = -71.05; // Example: Enter your longitude coordinates

  // Create a map object
  var map = new google.maps.Map(document.getElementById('map'), {
    center: {lat: latitude, lng: longitude},
    zoom: 12 // Initial map zoom level
  });

  // Add a marker with the obtained coordinates
  var marker = new google.maps.Marker({
    position: {lat: latitude, lng: longitude},
    map: map,
    title: 'Coordinates Here!'
  });
}

Step 3: Running the Tutorial

When you run your HTML file in a browser, you should see a Google Maps map with a marker indicating the specified coordinates.

Step 4: Understanding the Code

  • The initMap() function is the main function called by the Google Maps API to display the map.
  • latitude and longitude are your geographic coordinates you want to display.
  • The google.maps.Map class object is created with specified zoom and center coordinates.
  • The google.maps.Marker class object creates a marker with the specified coordinates.

Thatโ€™s how you can use JavaScript and the Google Maps API to display obtained geographical coordinates on your website. Keep in mind that this example is very basic, and you can expand it by adding more functionality and styling to your website.