Ramya Raj
Ramya Raj

Reputation: 109

Google Maps JavaScript API for ASP.NET MVC not working

I would like to use the Google Maps JavaScript API to display a map in my html View. I'm building a ASP.NET MVC web application. I have included the reference script, the initmap() function and the map div element. I'm getting an error that says 'initMap' is not a function in the console.Here's the code:

<script  defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCKLXdTfjmz8GlKELpyrmDxCgkkmAiy23c&callback=initMap">
</script>

<div id="map"></div>    
<script>
 $(document).ready(function () {
     });   
 function initMap() {
                    var uluru = {lat: -25.363, lng: 131.044};
                    var map = new google.maps.Map(document.getElementById('map'), {
                      zoom: 4,
                      center: uluru
                    });
                    var marker = new google.maps.Marker({
                      position: uluru,
                      map: map
                    });
                    console.log("Map initialized");
            }

    </script>

EDIT: I moved the initMap() function outside $(document)ready() and there were no errors. But the Map still doesn't show up on the screen.

Upvotes: 1

Views: 1465

Answers (1)

Classe
Classe

Reputation: 256

From what I remember, the scripts from maps.googleapis.com is the one calling for initMap().

So when you have that function declared after the script, it is not yet available. But there might already be a fallback for that in their script, but keep that in mind.

I think the real issue here is that you are using $(document).ready(). So, that comes from jQuery, and it's purpose is to wait for the document to be ready for scripts, before it executes.

In your case, it means it will wait for everything to load, before setting the function. (There is also a scoping issue that comes with it, but lets leave that for later)

So, simply remove the $(document).ready() around it, since Google is not using jQuery for their APIs.

Also, keep in mind that it is seldom required even when using jQuery, if you make sure you put your scripts in the bottom of the page. (There are some exceptions)

Edit: After your edit, I do believe it is the script order, if you still get the same error message.

Upvotes: 1

Related Questions