Mapping technologies provided by Google Maps Geocoding API are top-notch

I'm having an issue with the code below. It should display a map and a div section, but for some reason, it's not showing the marker point on the map. Can anyone provide assistance? Thank you in advance!

<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false">                                                            </script>

<script>
    var myCenter = new google.maps.LatLng(17.382094947877505,78.431396484375);
    var geocoder, map;

    function initialize() {
        geocoder = new google.maps.Geocoder();
        var mapProp = {
            center: myCenter,
            zoom: 5,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };

        var map = new google.maps.Map(document.getElementById("googleMap"), mapProp);
    }

    function codeAddress() {
        var address = document.getElementById('address').value;
        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 {
                alert('Geocode was not successful for the following reason: ' + status);
            }
        });
     }
     google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>

<body>
    <div id="panel">
        <input type="address" type="textbox" value="Hyderabad, Telangana">
        <input type="button" value="Geocode" onclick="codeAddress();">
    </div>
    <div id="googleMap" style="width:1200px;height:800px;"></div>
</body>
</html>

Answer №1

To ensure your code functions correctly, there are two key steps you must take:

  1. Ensure that your input field includes an id attribute (as you are utilizing document.getElementById)
  2. Avoid reinitializing the map variable

This is how the address input should be structured:

<input id="address" type="text" value="hyderabad, Telangana">

Map instantiation should follow this format:

map = new google.maps.Map(document.getElementById("googleMap"), mapProp);

Here is the complete code:

<!DOCTYPE html>
<html>
<head>
   <script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
   <script>
      var myCenter=new google.maps.LatLng(17.382094947877505,78.431396484375);
      var geocoder,map;

      function initialize() {
         geocoder = new google.maps.Geocoder();
         var mapProp = {
            center:myCenter,
            zoom:5,
            mapTypeId:google.maps.MapTypeId.ROADMAP
         };

         map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
      }

      function codeAddress() {
         var address = document.getElementById('address').value;
         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 {
               alert('Geocode was not successful for the following reason: ' + status);
            }
         });
      }

      google.maps.event.addDomListener(window, 'load', initialize);
   </script>
</head>
<body>
   <div id="panel">
      <input id="address" type="text" value="hyderabad, Telangana">
      <input type="button" value="Geocode" onclick="codeAddress();">
   </div>
   <div id="googleMap" style="width:1200px;height:800px;"></div>
</body>
</html>

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

What is the reason behind the CSS not rendering when async:false is used?

I find it peculiar and am actively seeking an explanation for this anomaly. In my code snippet, the AJAX call seems to be causing unexpected behavior: $('.edit-config').click(function() { var that = this; var msg; ip ...

What causes useEffect to trigger twice when an extra condition is included?

Attempting to create a countdown timer, but encountering an interesting issue... This code triggers twice in a row, causing the useEffect function to run twice per second. 'use client' import {useState, useEffect, useRef} from 'react' ...

The art of efficiently handling and outputting an array of files using node

In a folder filled with markdown files like so: myDir |- fileA.md |- fileB.md |- fileC.md |- fileD.md I want to extract just the filenames without the file extension and store them in an array. This is my attempt: var mdFiles = fs.readdir('myDir&a ...

Check the values in the folder and if the folder is not already in the array, add the object to the array. If the

In my directory tree, there are numerous sub-directories that contain even more sub-directories. Consider the structure: vvv example1 plugin1 plugin2 example2 plugin1 plugin2 plugin3 etc. I am trying to figure out how many times ...

What is the process of integrating data from the OpenWeatherMap API into the WindowInfo feature of Google Maps?

My current project involves retrieving weather information from the openweathermap API and displaying it in an infowindow on Google Maps. However, there seems to be an issue where I am getting data from the previous marker instead of the current one. var ...

Interactive drop-down feature where the toggle option is displayed exclusively in the initial drop-down menu

I am currently integrating Dropdowns into a dynamic form. However, I have encountered an issue when adding more than one Dropdown. Upon clicking on any Dropdown button, the list only appears above the first Dropdown button and not the specific one I click ...

Utilize jQuery to wrap text within <b> tags and separate them with <br> tags

Upon receiving output in html string format from services, I am presented with the following: "<html>↵<h1>↵Example : ↵<br>Explanation↵</h1>↵<hr>↵<b>key1 : ABCD <br>key2 : 2016-10-18-18-38-29<br> ...

Allow editing for only a specific part of a text box

Creating a customized personal URL page for users on my site is important to me. I envision the value of a text box being "example.com/username," with the "example.com/" part displayed in the text box, but not editable. I've noticed that Tumblr accom ...

My goal is to adjust the height of every text box on the page

Seeking guidance here. Within the webpage I'm developing, there are multiple 'Divs' containing 'text boxes' and 'background images' within them. I aim to adjust the height of each text box on the page. The height of each ...

JavaScript: Issue with hiding input BUTTON element - still not resolved

<input id="btnupdate" type="button" value="Update" onclick="update()"/> <img id="loadupdate" src="http://localhost/connectu/styles/images/load_big.gif"> This particular HTML code snippet is generated by a PHP script in response to an AJAX requ ...

What is the best way to showcase a circular dot to indicate active status in a React component

In previous versions of react, the code displayed either "active" or "inactive" for a user. I now want to change it to display a small red or green dot instead. How can I achieve this? ...

Verify whether an email is already registered in firestore authentication during the signup process using Angular

When a user signs up for our app, I want them to receive immediate feedback on whether the email they are attempting to sign up with already exists. Currently, the user has to submit the form before being notified if the email is taken or not. This desire ...

What is the best way to display information in a Handlebars template file?

Having trouble displaying data in the template using NestJS with mysql. Here is the code snippet from controller.ts: import { Controller, Get, Post, Put, Delete, Body, Param, Render, UsePipes, Logger, UseGuards} from '@nestjs/common'; import { P ...

Converting a variety of form fields containing dynamic values into floating point numbers

Trying to parse the input fields with a specific class has presented a challenge. Only the value of the first field is being parsed and copied to the other fields. https://i.stack.imgur.com/QE9mP.png <?php foreach($income as $inc): ?> <input ty ...

Using ng-bind-html within a ng-repeat loop

Currently, I am working on developing a custom autosuggest feature where a web service is queried with a search term to retrieve a list of suggestions that are then displayed. My main obstacle lies in trying to highlight the matching term within the sugges ...

Transform Dynamic Array to JSON structure

I am currently developing a feature in my SvelteKit application that allows users to create custom roles for themselves. Users can input a role name and add it to an array, which is then displayed below. https://i.stack.imgur.com/oUPFU.png My goal is to ...

Steer clear of duplicating patterns in vue templates

I have a significant issue with a component that needs to be repeated multiple times in the parent template due to the usage of v-if. The component code is as follows: <SelectCard v-for="(channel, index) in category.visibleChannels" :key="index + & ...

Tips on how to showcase particular keys from json information in React

Here is a sample of Json data that I have: [ { "serial_number": "test1", "added_at": "2021-02-05T18:58:43.382943Z", "ser_mod": [ { "added_at": "2021-02-06T02: ...

Merging object destructuring with flow-typing

Recently integrated Flow into my Create-React-App project, and while updating some of my calculation code to flow-typed, I encountered an issue with object destructuring. Here is the original signature: calcWeightOnConveyor({ tonsPerHour, conveyorLength, ...

Combining Protractor, CucumberJS, and Gulp-Protractor results in the browser not closing when a test fails

Hello! I am facing an issue with closing the browser when a test fails. Currently, the browser closes successfully when the test passes. The dependencies I am using are: "cucumber": "^0.9.2", "gulp": "~3.9.0", "gulp-protractor": "^2.1.0", "protractor": ...