Finding multiple locations with Google Maps API Geocoding

I've created a small JavaScript code to geocode various locations and display them on a map. While I can successfully plot a single location, I'm struggling to get it working for multiple locations. Below is the code that currently works for one location only.

var geocoder = new google.maps.Geocoder();
    var address = "Melbourne";

    geocoder.geocode( { 'address': address}, function(results, status) {

        var latitude = results[0].geometry.location.lat();
        var longitude = results[0].geometry.location.lng();


        initialize(latitude,longitude);

        }); 


    function initialize(latitude,longitude) {
        var latlng1 = new google.maps.LatLng(latitude,longitude);

        var myOptions = {
          zoom: 2,
          panControl: false,
            zoomControl: false,
            mapTypeControl: false,
            streetViewControl: false,
          center: latlng1,
          mapTypeId: google.maps.MapTypeId.ROADMAP,
          mapTypeControl: false,
          scrollwheel: false,
        };
        var map = new google.maps.Map(document.getElementById("google-container"),myOptions);

        var marker = new google.maps.Marker({
          position: latlng1, 
          map: map, 
        }); 
      }

I attempted to add a second location with the code below, but it seems I missed something important. It's clear that I'm still learning JavaScript.

    var geocoder = new google.maps.Geocoder();
var address = "Seoul";
var address2 = "Melbourne";

geocoder.geocode( { 'address': address}, function(results, status) {

    var latitude = results[0].geometry.location.lat();
    var longitude = results[0].geometry.location.lng();


    initialize(latitude,longitude);

    }); 

    geocoder.geocode( { 'address': address2}, function(results, status) {

    var latitude2 = results[0].geometry.location.lat();
    var longitude2 = results[0].geometry.location.lng();


    initialize(latitude2,longitude2);

    }); 


function initialize(latitude,longitude) {
    var latlng1 = new google.maps.LatLng(latitude,longitude);
    var latlng2 = new google.maps.LatLng(latitude2,longitude2);

    var myOptions = {
      zoom: 2,
      panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false,
      center: latlng1,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      mapTypeControl: false,
      scrollwheel: false,
    };
    var map = new google.maps.Map(document.getElementById("google-container"),myOptions);

    var marker = new google.maps.Marker({
      position: latlng1, 
      map: map, 
    }); 
      var marker2 = new google.maps.Marker({
      position: latlng2, 
      map: map, 
    }); 
  }

Any thoughts or suggestions would be greatly appreciated!

Answer №1

This solution is effective for managing a small number of locations, typically between two and ten. However, as the number of locations increases, it is important to be mindful of potential query and rate limits on the Geocoder

  1. One approach is to separate out the initialize function, which is responsible for setting up the map.
  2. It is recommended to create a distinct geocoder instance for each location. While it is possible to reuse the same geocoder instance by utilizing it in the callback function, this may not be efficient for only two points.

Here is a working fiddle

For reference, below is a snippet of the functional code:

function initialize() {
    var myOptions = {
        zoom: 2,
        panControl: false,
        zoomControl: false,
        mapTypeControl: false,
        streetViewControl: false,
        center: {
            lat: 0,
            lng: 0
        },
        mapTypeId: google.maps.MapTypeId.ROADMAP,
        mapTypeControl: false,
        scrollwheel: false,
    };
    var bounds = new google.maps.LatLngBounds();
    var map = new google.maps.Map(document.getElementById("google-container"), myOptions);
    var geocoder = new google.maps.Geocoder();
    var address = "Seoul";

    geocoder.geocode({
        'address': address
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
            });
            bounds.extend(results[0].geometry.location);
            map.fitBounds(bounds);
        } else {
            alert("Geocode of " + address + " failed," + status);
        }
    });
    var geocoder2 = new google.maps.Geocoder();
    var address2 = "Melbourne";
    geocoder2.geocode({
        'address': address2
    }, function (results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            var marker = new google.maps.Marker({
                position: results[0].geometry.location,
                map: map,
            });
            bounds.extend(results[0].geometry.location);
            map.fitBounds(bounds);

        } else {
            alert("Geocode of " + address2 + " failed," + status);
        }
    });
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #google-container {
    height: 100%;
    width: 100%;
    margin: 0px;
    padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<div id="google-container" style="border: 2px solid #3872ac;"></div>

Answer №2

Below is an example of optimizing code to process multiple addresses efficiently:
      <div id="map-canvas"
   style='position: relative; height: 100%; width: 100%; margin-left: 0px; border: #B8B6B8 solid 1px;; background-color: #ffffff;'>
  </div> 
<script type="text/javascript">
    var geocoder;
    var map;

    function initialize() {
        geocoder = new google.maps.Geocoder();
        var latlng = new google.maps.LatLng(-34.397, 150.644);
        var mapOptions = {
            zoom : 17,
            center : latlng,
            mapTypeId : google.maps.MapTypeId.ROADMAP
        };
        map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
    }

    function codeAddress(addressList) {
        try {
            var icount = addressList.length;
            for (var i = 0; i < icount; i++) {
                getGeoCoder(addressList[i]);
            }
        } catch (error) {
            alert(error);
        }
    }

    function getGeoCoder(address) {
        geocoder.geocode({
            'address' : address
        }, function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                map.setCenter(results[0].geometry.location);
                var marker = new google.maps.Marker({
                    map : map,
                    position : results[0].geometry.location
                });
            } else {
                geterrorMgs(address); // handle address not found
            }
        });
    }

    // Client's call - List of addresses to be processed
    var addressList = [ '1420 orchardview dr Pittsburgh,  PA,  USA', '1440 orchardview dr Pittsburgh,  PA,  USA', '1410 orchardview dr Pittsburgh,  PA,  USA' ];
    
    initialize();  
    codeAddress(addressList);
</script>

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

The Ajax search box displays results from the most recent query

Hey there, I need some assistance with a request: var searchResults = new Array(); var ajaxRequest = function (value, type) { if (typeof(type) === "undefined") type = "default"; var ajaxData = { "title" : value, "limit" : ...

Avoid sudden page movements when validating user input

After successfully implementing the "Stars rating" feature from https://codepen.io/462960/pen/WZXEWd, I noticed that the page abruptly jumps up after each click. Determined to find a solution, I attempted the following: const labels = document.querySelect ...

ClassNames Central - showcasing a variety of class names for interpolation variables

Seeking guidance on creating a conditional statement to set the className for a div element. The conditional is functioning correctly, and I can see the className being assigned properly in the developer console. However, I am struggling to return it as ...

Webpack has made Rails .js.erb templates obsolete

Recently, I migrated my Rails application to use WebPack for handling assets, and it has been operating smoothly. However, I encountered an issue with JS templates located in my views directory (*.js.erb) that require jQuery. Since jQuery is included in my ...

Retrieve JSON and HTML in an AJAX request

I have multiple pages that heavily rely on JavaScript, particularly for sorting and filtering datasets. These pages typically display a list of intricate items, usually rendered as <li> elements with HTML content. Users can delete, edit, or add item ...

Sorting numbers in JavaScript from highest to lowest

I have the following variables: let var1 = 20; let var2 = 10; let var3 = 40; let var4 = 9; let var5 = 6; let var6 = 51; I am looking for a way to sort these variables from highest to lowest, and return their names in the sorted ...

Navigating through a JavaScript object array within another object

I am looking to iterate through a JavaScript object array Here is my object response: { "kind": "calendar#events", "etag": "\"p3288namrojte20g\"", "summary": "pedicura", "updated": "2019-05-01T14:25:51.642Z", "timeZone": "America/Argentina ...

Guide to sending an array to a Node.js web service using AngularJS

Attempting to add an array of data to a Node.js web service using the code below. $scope.addList = function(task,subtask){ subtask.checked= !(subtask.checked); var data = { "taskId": task._id, "subTaskName": subtask.subTaskNa ...

Developing a Typescript module, the dependent module is searching for an import within the local directory but encounters an issue - the module cannot be found and

After creating and publishing a Typescript package, I encountered an issue where the dependent module was not being imported from the expected location. Instead of searching in node_modules, it was looking in the current folder and failing to locate the mo ...

Update the knockout values prior to submitting them to the server

Imagine having a ViewModel structured like this with prices ranging from 1 to 100... var Item = { price1: ko.observable(), price2: ko.observable(), price3: ko.observable(), ... ... price100: ko.observable(), name: ko.observable ...

Once the AJAX callback is complete, the onblur event will revert back to the original field or the updated field

I am currently working with an AJAX callback: Here is the HTML snippet: <a onCLick="loadXMLDoc(id1,id2)">(Add)</a> This function triggers an AJAX method that replaces the "(Add)" text with a basic HTML input field. Subsequently, when there ...

Do window.location.href and window.open interfere with each other?

I'm attempting to open a PDF in a new URL and redirect the user to the homepage at the same time. However, these two conditions in the "if" block are conflicting with each other. The page successfully redirects to the homepage, but the window.open() f ...

What is the best way to combine two sections in html/css/bootstrap?

I've been trying to create a simple webpage with a navigation bar and a section below it, but I keep running into an issue where there's unwanted white space between the nav bar and the next section in blue. Is there a way to eliminate this gap a ...

Steps to update the package version in package.json file

If I remove a package from my project using the following command: npm uninstall react The entry for this package in the package.json file does not disappear. Then, when I install a different version of this package like so: npm install <a href="/cdn ...

Exploring the world of lighting and shadows in WebGL and Three.js

I'm having difficulty focusing lights on specific targets, specifically the main character, while also darkening the background. Additionally, I'm experiencing issues with the shadows not working properly in my code snippet related to lights and ...

"Troubleshooting issues with Material Design components in AngularJS: Why is <md-select> not functioning correctly

I'm attempting to implement the <md-select> tag, but I can't seem to achieve the same result as shown here. This is the code I've written: <div layout="column" layout-align="center center" style="margin: 0px 10px 0px 5px;"> & ...

How can I successfully implement the Add To Calendar Button Package?

Recently, I decided to incorporate this particular component into my application. Although it seemed simple enough at first, I'm now faced with a puzzling TypeError originating from within the package. The react component I am constructing is as foll ...

Implementing recursive functionality in a React component responsible for rendering a dynamic form

Hello to all members of the Stack Overflow community! Presently, I am in the process of creating a dynamic form that adapts based on the object provided, and it seems to handle various scenarios effectively. However, when dealing with a nested objec ...

Loading pages asynchronously using Ajax with added interactivity through custom JavaScript scripts

Using jQuery Masonry in conjunction with another JavaScript for voting, here is the code: <div id="contain"> <?php $result = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 0, 20"); while($row = mysqli_fetch_array($result ...

Can the swap operation be carried out using web3.js and a forked HardHat implementation?

Embarking on my journey into ethereum development, I am currently engrossed in crafting a basic script that facilitates swaps using web3.js. To begin with, my web3 is establishing a connection to the HardHat forked server. The first step involves setting ...