Experience the full functionality of Google Maps API without the need for jQuery or PHP with PanTo

I'm not a developer and I find myself stuck in the panTo() function. All I want is to execute this function with an if-else statement without having to reload the Google Map or using jQuery.

<body>
    <div id="map"></div>
    <div>
        <ul>
            <li><a href="#" id="abc" onclick="main(1)">A</a></li>
            <li><a href="#" id="def" onclick="main(2)">B</a></li>
            <li><a href="#" id="ghi" onclick="main(3)">C</a></li>
            <li><a href="#" id="jkl" onclick="main(4)">D</a></li>
        </ul>
</body>
</div>

 <script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFX2v5z34vYKl0We4nHV4KFV1j6uVsltg&callback=main"></script>

Here's the function:

function main(number) {
var map;
var map= {
    center:new google.maps.LatLng(33.72939,73.09315),
    zoom:10,
    };

if (number==1) {
    map.setCenter(51.508742,-0.120850);
}else if (number==2) {
    map.setCenter(33.72939,73.09315);
}else if (number==3) {
    map.setCenter(33.939445,73.34587);
}else{
    alert("Sorry! No Place found with name ")
}
var map1= new google.maps.Map(document.getElementById("map"),map);
}

Answer №1

Correction needed: Change map.setCenter( "lat", "lng" ); to map.setCenter( latLngObject );

// Keep your code simple, avoid unnecessary else/if statements!

var locations = { // name : [lat, lng]
  "1" : [51.508742, -0.120850],
  "2" : [33.72939, 73.09315],
  "3" : [33.939445, 73.34587]
};

// Map Object Initialization
var map = new google.maps.Map(document.getElementById("map"), {
  zoom: 16,
});


function main( name ){
  
  if(!(name in locations)) return alert("No location found with the name: "+ name);
  // Create a new LatLng Object
  var latLng = new google.maps.LatLng( locations[name][0], locations[name][1] );
  map.setCenter( latLng );
}


// Initialize map using location name "2"
main("2");
#map{height:200px;}
li {display: inline-block;} li a{cursor: pointer;}
<ul>
  <li><a id="abc" onclick="main(1)">A</a></li>
  <li><a id="def" onclick="main(2)">B</a></li>
  <li><a id="ghi" onclick="main(3)">C</a></li>
  <li><a id="jkl" onclick="main(4)">D</a></li>
</ul>
  
<div id="map"></div>  
  
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBFX2v5z34vYKl0We4nHV4KFV1j6uVsltg"></script>

Additionally, note that I have removed the &callback from the Google Maps URI

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

Leverage the power of Laravel and ReactJS to beautifully display images

Currently, I am working on a project where I am incorporating ReactJS into a Laravel blade file. To get started, I included the React CDN and began writing code within the script tag. Everything seems to be going smoothly so far, however, I have encountere ...

Create a unique Bitcoin address using a derivation scheme

Starting with a derivation scheme that begins with tpub... for the testnet, I am looking to generate bitcoin addresses from this scheme. I also need a method that will work for the mainnet. Is there a library available that can assist me with this task? ...

enhancing look of external tool

I have a third-party widget with inline CSS that displays a table on my website. Is there a way to strip out the inline CSS from the widget before adding it to my page so that only my custom css file styles are applied? The HTML structure of the widget i ...

Is there a way to link dynamic server fields with VueJS?

How can I bind data posted by the server with Vue.js in order to display the data instead of field names? <script> module.exports = { data: function () { return { filedNameFromServer: ['{{filed1}}' ...

The height percentage is not functioning properly even though it has been applied to the html, body, and all wrapper elements

I've been facing a persistent challenge with the height:100% problem. It seems like it should be an easy fix by ensuring all wrapper elements and html, body have height:100%, but no matter what I try, the containers still won't reach the bottom o ...

css - targeting the last child element using a type selector

I'm attempting to target the final child element of type <div> within the container "#myDiv" <div id="myDiv"> <div> <img> <div> <div>text</div> ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

How can I trigger my function in jQuery after inputting into the jQuery text field?

Looking for advice on implementing a function in jQuery for a text field that is not working as expected. The code works fine when creating a text field in HTML, but encounters issues with the jQuery text field. <!DOCTYPE html> <html> <body ...

Is there a way to upload several documents in just one writing?

Can anyone advise me on how to add multiple documents to my Firestore collection using just one write operation? I have over 20,000 records and I'm looking for a cost-effective solution. Is there a way to add multiple docs in a single write? Apprecia ...

Refresh Layers in Openlayers with LayerRedraw(), Rotate Features, and Manipulate Linestring Coordinates

TLDR: I am facing difficulties with my OpenLayers map. Specifically, I want to remove and add a layer called 'track', or find a way to plot a triangle based on one set of coordinates and a heading (see below). In my OpenLayers map, there is an i ...

v-treeview component triggering method execution twice upon input

I'm facing an issue with my Vue component that contains a treeview. Upon selecting a node, the goal is to update an array and display the checkbox as selected. However, I'm encountering a problem where if I select elements from one folder in the ...

What is the solution for resolving the problem of the cursor jumping to the end when converting numbers in JavaScript?

After exploring the inquiries regarding converting digits in JavaScript, such as What's the solution and the right way to convert digits in JavaScript? and How to convert numbers in JavaScript, and problems with commands to remove non-numeric characte ...

Extracting the value of *data* from my HTML and displaying it in the console with Javascript

I'm struggling to figure out what's going wrong with this code. I've done some research online and it seems like I should just include the window.onload = function() at the beginning of my code. However, no matter what I try, the value alway ...

Is it better to convert fields extracted from a JSON string to Date objects or moment.js instances when using Angular and moment.js together?

When working on editing a user profile, the API call returns the following data structure: export class User { username: string; email: string; creationTime: Date; birthDate: Date; } For validating and manipulating the birthDate val ...

Is it possible to extract a specific value from JSON data by making an AJAX call or applying a filter to the fetched JSON data?

I have been utilizing a treeview template and successfully displaying all the data. However, I am facing an issue where I need to pass a value from index.php to getdata.php. I attempted using an AJAX filter on the index.php page and also tried sending a v ...

Programmatically link an Angular JS model to a template using binding

When given an HTML template like the following: <div class="info"> <div class="title"><a href="property-detail.html">{{title}}</a></div> <div class="location">{{location}}</div> <div class="property ...

Troubleshooting error in WordPress: Changing innerHTML of dynamically created divs using JavaScript. Issue: 'Unable to set property innerHTMl of null'

I am struggling to modify the innerHTML of a "View cart" button using a dynamically generated div class on my Wordpress/Woocommerce site. In a previous inquiry, I was informed (thanks to Mike :) ) that since JavaScript is an onload event, the class changes ...

Using Javascript, incorporate a string variable into the response

Currently, I'm working with a node.js program and I've come across this response: 'Content-Disposition': 'attachment; filename="tts.mp3"' Instead of using "tts.mp3," I have a variable named textToConvert. How can I modify it ...

There seems to be a hiccup in the JavaScript Console. It could potentially impact the functionality

Hey there, I'm encountering a strange issue in my IE 11 console. A JavaScript Console error has occurred. This may impact functionality. Whenever I try to run a for loop to create a list of elements within a ul tag 4000 times, the process stops at ...

Using PHP to iterate through an array and output the values within a

Hey there! I have a question about incorporating PHP foreach and echo into JavaScript to make it dynamic. Here is the current static JavaScript code: <script type="text/javascript"> $(document).ready(function(){ $('input[type="checkbox"]&ap ...