Using an array to set the center of a map - Google Maps API

I'm attempting to populate a HTML menu with values from a JavaScript multidimensional array using setCenter.

Example of HTML Menu

 <li><a onclick="map.setCenter(cityList[0][1], cityList[0][2]); return false"><script>document.write(cityList[0][0]);</script> </a></li>

JavaScript Array

  var cityList = [
    ['Atlanta, GA', 33.840644, -84.238972, 1],
    ['Austin, TX', 30.402887, -97.721606, 2],
    ['Boston, MA', 42.364247, -71.078575, 3],
    ['Chicago, IL', 41.898111, -87.638394, 4]
];

I have also attempted this with a Custom Control, but encountered the same issue:

  google.maps.event.addDomListener(btnAtl, 'click', function() {
    map.setCenter(cityList[0][1], cityList[0][2])
  }); 

Error in Console

  Uncaught InvalidValueError: setCenter: not a LatLng or LatLngLiteral: not an Object

Answer №1

Referenced from the official documentation.

When using google.maps.Map.setCenter, you can provide either a google.maps.LatLng or a LatLngLiteral as an argument.

Here is an example of how this can be implemented:

<li><a onclick="map.setCenter(new google.maps.LatLng(cityList[0][1], cityList[0][2])); return false"><script>document.write(cityList[0][0]);</script> </a></li>

Below is a functioning code snippet:

var map;
var cityList = [
  ['Atlanta, GA', 33.840644, -84.238972, 1, "text 0"],
  ['Austin, TX', 30.402887, -97.721606, 2, "text 1"],
  ['Boston, MA', 42.364247, -71.078575, 3, "text 2"],
  ['Chicago, IL', 41.898111, -87.638394, 4, "text 3"]
];

function initialize() {
  var mapOptions = {
    zoom: 6,
    center: new google.maps.LatLng(46.8, 1.7),
    mapTypeId: google.maps.MapTypeId.ROADMAP
  }

  map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);

  setMarkers(map, cityList);
}

function setMarkers(map, locations) {
  var bounds = new google.maps.LatLngBounds();
  var image = 'http://maps.google.com/mapfiles/ms/icons/blue.png';
  for (var i = 0; i < locations.length; i++) {
    var city = locations[i];
    var myLatLng = new google.maps.LatLng(city[1], city[2]);
    bounds.extend(myLatLng);
    var infoWindow = new google.maps.InfoWindow();
    var marker = new google.maps.Marker({
      position: myLatLng,
      map: map,
      icon: image
    });
    document.getElementById('sidebar').innerHTML += '<li><a onclick="map.setCenter(new google.maps.LatLng(' + city[1] + ',' + city[2] + ')); return false">' + city[0] + '</a></li>';

    (function(i) {
      google.maps.event.addListener(marker, "click", function() {
        var galeries = locations[i];
        infoWindow.close();
        infoWindow.setContent(
          "<div id='boxcontent'><a href='" + city[0] + "'><strong style='color:black'>" + galeries[0] + "</strong></a><br />" + city[4] + "</div>");
        infoWindow.open(map, this);
      });
    })(i);
  }
  map.fitBounds(bounds);
}

google.maps.event.addDomListener(window, 'load', initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<table border="1" style="height:100%; width:100%">
  <tr style="height:100%; width:100%">
    <td style="height:100%; width:80%">
      <div id="map_canvas" style="border: 2px solid #3872ac;"></div>
    </td>
    <td style="height:100%; width:20%">
      <div id="sidebar"></div>
    </td>
  </tr>
</table>

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

Android Chrome users experiencing sidebar disappearance after first toggle

Over the past few days, I've dedicated my time to developing a new project. I've been focusing on creating the HTML, CSS, and Java layout to ensure everything works seamlessly. After completing most of the work, the design looks great on desktop ...

The react-bootstrap implementation is not functioning as expected, resulting in an unsupported server component error

Having an issue with an Unsupported Server Component Error while using react-bootstrap with typescript. I've shared the contents of my page.tsx file, layout.tsx file, and the specific error message. layout.tsx file import type { Metadata } from &apos ...

How to display nested arrays in AngularJs

Within my array contacts[], there are multiple contact objects. Each of these contact objects contain an array labeled hashtags[] consisting of various strings. What is the best way to display these hashtags using ng-repeat? ...

Enabling specific special characters for validation in Angular applications

How can we create a regex pattern that allows letters, numbers, and certain special characters (- and .) while disallowing others? #Code private _createModelForm(): FormGroup { return this.formBuilder.group({ propertyId: this.data.propertyId, ...

Switch the design and save it in the browser's cache

Exploring the possibility of having two themes, "dark" and "light," that toggle when a checkbox is clicked. To implement the theme change, I used the following JavaScript code: document.documentElement.setAttribute('data-theme', 'dark&apos ...

Python - Organizing massive collection into separate parts

Currently, I am working on processing a map that contains 750 x 750 numbered tiles stored as JSON data. My goal is to retrieve this data and divide each tile into separate arrays or chunks. I have successfully implemented the code for this task; however, ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Hide and show submenus with jQuery while ensuring that the initial submenu remains visible, along with the main menu

I am struggling to figure out how to make the first message active by default along with its corresponding menu selection in my navbar. I have implemented a show/hide functionality on the main menu click, but currently only the menu is being set as active ...

Route fallback not yet resolved

Is it possible to set up a fallback route in angular routes? For instance, is there a way to specify a fallback route like this: $routeProvider .when('/a', { templateUrl: 'a.html', controller: 'aCtrl' ...

Resolving issues with setting up d3.js in the 'Creating a Custom Map' guide

Starting Mike Bostock's tutorial on creating a map, but facing some installation issues at the beginning. I am using Windows 8.1 for this. This is the specific part that's causing trouble: "To get started, you'll need the reference implemen ...

Resize the div based on the width and height of the window

My goal is to create a system or website that can be fully resizable using CSS and the VW (viewport width) unit. Within this system, I have integrated a GoogleChart that functions with pixels. Now, I am looking for a way to scale the chart using Javascript ...

What causes the HTML element's X position value to double when its X position is updated after the drag release event in Angular's CDK drag-drop feature?

I am facing a challenge with an HTML element that has dual roles: Automatically moving to the positive x-level whenever an Obsarbalve emits a new value. Moving manually to both positive and negative x-levels by dragging and dropping it. The manual drag a ...

To activate two separate click events, one for an absolute element and another for the element positioned behind it, simply click on the desired absolute element to trigger both actions

Is it possible to trigger click events for both of these elements? position: relative container ELEMENT 1: standard div ELEMENT 2: position: absolute div In real life, element 2 is a transparent backdrop designed to capture clicks on top of the header ...

Tips for showcasing content on a jQuery calendar

I have a jQuery calendar implemented on my website and I would like to show a list of local holidays on the calendar. The calendar is functioning correctly with the script below, but I just need help displaying the holidays. <script> $(document).r ...

Experiencing a 404 ERROR while attempting to submit an API POST request for a Hubspot form within a Next.js application

Currently, I am in the process of developing a Hubspot email submission form using nextjs and typescript. However, I am encountering a couple of errors that I need help with. The first error pertains to my 'response' constant, which is declared b ...

"Learn the technique of animating SVG paths with JavaScript, a step beyond traditional HTML filling

I am looking to animate SVG path elements with JavaScript instead of HTML. I have come across numerous articles discussing how to achieve this through JavaScript and jQuery by manipulating the attributes. Some helpful links I found: Fill color SVG path w ...

Using Spry Validate for form validation in conjunction with Ajax submission

I'm currently facing an issue where I want my form to validate before the ajax call is made, but I can't seem to figure out the correct coding for this process. When I separate them, I am able to either post using ajax without validation or with ...

Having difficulty personalizing the email template on AWS SES

I am currently working on setting up a forgot password email system using AWS SES. Below is the template I have created: { "Template":{ "TemplateName": "forgotpasswrd", "SubjectPart": "Forgot ...

Seeking a way to keep the returned Ajax string consistent and prevent it from fading away after page transition

I have a form that appears when the user clicks on the "Edit" link, allowing them to input their profile information. Upon submission, the data is processed via Ajax and saved in an SQL database using a PHP script. After saving the new profile, I would lik ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...