What steps can I take to stop Google Maps from resetting after a geocode search?

As a beginner working with the Google Maps Javascript API v.3, I have written some code to initialize a map, perform an address lookup using the geocoder, re-center the map based on the obtained lat long coordinates, and place a marker. However, I am facing an issue where the page triggers another onLoad event after recentering and placing the marker, causing the initialize() function to reset all variables. Despite spending hours trying to figure out the cause, I am still unsure why this extra onLoad event is happening. Can anyone help me identify the root of this problem?

Furthermore, since I am new to JavaScript programming and Google maps integration, any suggestions on improving code quality would be greatly appreciated. I have attempted to scope several variables globally, but I am uncertain if I have done it correctly.

Here is the current code snippet (please note that I intend to replace the setTimeout function in the future once I become more proficient in handling asynchronous calls):

<script type="text/javascript">
               var map;
               var geocoder;
               var marker;
               var latlng;
               function initialize() {
                   geocoder = new google.maps.Geocoder();
                   var mapOptions = {
                                     center: new google.maps.LatLng(47.606, -122.314),
                                     zoom: 12
                                    };
                   if (this.map == null){
                      this.map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
                    }
                }

  
  function checkResponse(results, response){
       if (response == google.maps.GeocoderStatus.OK) {
           this.latlng = results[0].geometry.location;
           this.map.setCenter(results[0].geometry.location);
           this.marker = new google.maps.marker({ map: map, position: results[0].geometry.location});
        } else {
           alert("Geocode was not successful for the following reason: " + response);
        }

    }
                                    
function searchAddress(){
     var address = document.getElementById('address1').value;
     var state = document.getElementById('state1').value;
     var zip = document.getElementById('zip1').value;
     var addressInput = address + ',' + state + ',' + zip;

geocoder.geocode( { 'address': addressInput}, function(results, status) {
  //ToDo remove this setTimeout function and replace it with a callback
        setTimeout(checkResponse(results, status), 3000);
    });
}
              
google.maps.event.addDomListener(window, 'load', initialize);
</script>

Answer №1

To prevent the page from reloading when using a JavaScript function as the onsubmit handler for a form, you must ensure that the function returns false.

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

Tips for effectively combining an array with jQuery.val

My goal is to have multiple form fields on a page, gather the input results into an array, and then store them in a database. This process was successful for me initially. However, when I introduced an autocomplete function which retrieves suggestions from ...

What is the reason behind router.base not functioning properly for static sources while running 'npm run build' in Nuxt.js?

Customizing Nuxt Configuration const BASE_PATH = `/${process.env.CATEGORY.toLowerCase()}/`; export default { router : { base : BASE_PATH }, } In addition, there is a static source for an image in the component: <img src="/mockups/macbookpro_01. ...

How can you modify a button in Ionic 2 based on the login status, using a modal to redirect to a different page once authenticated?

I have a button on my main page that is supposed to display 'Log out' when the user is currently logged in, and 'Log in' when there is no active user session. Clicking on the login button opens a modal. After successful login, the user ...

Struggling to retrieve information from MongoDB database for the web application

As someone new to the realm of MongoDB, I have been working on a web application that requires data storage. To handle this, I set up an HTTP server using Node.js on localhost:3000. Additionally, I created a virtual development environment using Vagrant an ...

The placeholder text in the matInput field is not being displayed

As a newcomer to Angular, I am facing a challenge that has left me unable to find a solution. Below is the code snippet in question: <mat-form-field> <input matInput placeholder="ZIP" style="color:red;"> </mat-form-field& ...

What steps can I take to deactivate input and stop it from being accessible on the browser?

insert image description Is there a method to block users from accessing disabled input fields in the browser? Any recommendations or solutions would be greatly appreciated. Vuejs is utilized within my project. Implementing this feature serves as a secu ...

Instructions for printing a page and closing the Print window using Selenium

New to using Selenium: I tried the following code in Selenium to open the print window, but unfortunately it doesn't seem to work Keyboard keyboard = ((HasInputDevices)driver).getKeyboard(); keyboard.pressKey(Keys.ENTER); keyboard.pressKey(Keys.ch ...

How to set the element in the render method in Backbone?

Currently, I am in the process of developing a web page utilizing BackboneJS. The structure of the HTML page consists of two divs acting as columns where each item is supposed to be displayed in either the first or second column. However, I am facing an is ...

Having trouble exporting data from Excel using react-data-export

I've been attempting to create an excel export feature, but for some unknown reason, it's not functioning properly. I'm utilizing react-data-export and followed a small test example from this GitHub link, yet the export is not working as exp ...

The React.js search feature consistently retrieves identical content every time

I am currently working on a project to create a search engine using React.js, specifically to search for GIPHY gifs through their API. However, I have encountered an issue where the gifs displayed do not update when I type in new words after erasing the pr ...

Swap out flash for javascript

I am embarking on a new task: replacing the flash element with JavaScript on this page: (switching images for buttons for each image) Naturally, it must maintain the same appearance and functionality. I have come across some jQuery modules that achieve s ...

What is the best way to align an InputAdornment IconButton with an OutlinedInput in Material-UI?

Struggling to replicate a text input from a mockup using Material-UI components. Initially tried rendering a button next to the input, but it didn't match. Moving on to InputAdornments, getting closer but can't get the button flush with the input ...

Guide on accessing and displaying data table values in console.log using Vue.js and vuetify

Hello, I am new to Vue.js and I am trying to work with data tables. I have copied some code from the Vuetify website and I am attempting to call the desserts' names from a sample table using console.log. Below is the code snippet: <template> ...

"React - encountering issues with state being undefined when passing child state up through parent components

I am currently navigating the world of react and have encountered a hurdle. I find myself facing difficulties in updating the parent component based on changes in the child state. I was able to pass the child state to the parent by linking the child's ...

Why isn't the externally loaded JS file executing properly?

My javascript code functions properly when it's embedded within the HTML file. However, I encounter issues when I try to import it externally. The Google Developer Tools indicate that the file has been loaded successfully, but there seems to be no vis ...

Incorporating <span> elements into a comma-separated list using Jquery on every other item

When I receive a comma-separated list of items from a database and insert them into a table cell, I want to apply alternating styles to make it easier for users to distinguish between them. For example: foo, bar, mon, key, base, ball I'm looking to ...

Leveraging the Power of jsPDF in Your Google Apps Scripts

Is it feasible to integrate jsPDF into a Google Apps Script project? I am attempting to create documents using templated HTML, but certain CSS styles like background-color do not translate to PDF when using the getAs() function. Given the limitations of ...

Material selection through span in three.js is not functional

Initially, the span element was functioning properly for me. However, after setting up materialsLib and initMaterialSelectionMenus based on the documentation and examples, the span stopped working and now the model is not visible. Any assistance would be g ...

Troubleshooting: CSS Styles not loading when passed as property in MUI withStyles

I am currently working on a react component that has a specific style defined as shown below: const StyledInnerItem = withStyles((theme) => ({ bgColor: { backgroundColor: (props) => { console.log('styledInnerItem color: ', props ...

Leveraging JavaScript event handlers within a progress wizard located within an update panel

I need assistance with implementing a password strength meter for a textbox within a wizard control. The issue I'm facing is that the password box does not become visible until step 4, preventing me from registering an event handler onload(). Placing ...