Reputation: 79
I am trying to use Google Gecoding API so that I can get the coordinates from a street address and use it with Google Maps. When I was just using the Google map I had no problems getting it to work. I have been following a guide since I don't really understand JavaScript. I get the error
ReferenceError: google is not defined
when I open the inspect element console.
I have been googling and I think the problem is that the map is not initialized when I run the first part of my JavaScript, since I only get the error on the Geocoding part. But I don't know what to do or how to fix it. Would appreciate some help.
Here is my view:
<div class="full">
<div class="saloon-main col-md-8">
<h1 class="display-2">@Model.SaloonName</h1>
<p class="saloon-adress">Andress 99 PostNr, Stad / TelNr: +46 21-123 45</p>
<button type="button" class="btn-primary">Boka tid</button>
</div>
<div class="company-right-nav col-md-4">
<div class="col-sm-12 saloon-info">
<ul class="list-unstyled">
<li>@Model.SaloonName</li>
<li>Email: @Model.Email</li>
<li>Telefon</li>
<li>Adress</li>
</ul>
<ul>
<li>ÖPPETTIDER</li>
<li>Måndag:</li>
</ul>
</div>
<div id="map">
<p>map</p>
</div>
</div>
<div class="clear"></div>
</div>
<script>
geocoder = new google.maps.Geocoder();
function getCoordinates (adress, callback) {
var coordinates;
geocoder.geocode({ adress: adress }, function (results, status) {
coords_obj = results[0].geometry.location;
coordinates = [coords_obj.nb,coords_obj.ob];
callback(coordinates);
})
}
var map;
function initMap() {
getCoordinates('4203 las palmas austin texas', function(coords) {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(coords[0], coords[1]),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'),
mapOptions);
})
}
google.maps.event.AddDomListener(window, 'load', initMap);
</script>
<script async defer src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDfKu9XJ0jr19cj46HYSqQrNDU-oX0LKmY&callback=initMap"
type="text/javascript"></script>
Upvotes: 0
Views: 1573
Reputation: 627
Try below code
No need to trigger event. initMap will automatically call when the library finish loading.
var map;
function initMap() {
geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': '4203 las palmas austin texas' }, function (results, status) {
if (status == 'OK') {
coords_obj = results[0].geometry.location;
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(coords_obj.lat(), coords_obj.lng()),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map'), mapOptions);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
<style>
#map {
position: unset !important;
}
</style>
<script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDfKu9XJ0jr19cj46HYSqQrNDU-oX0LKmY&callback=initMap"></script>
<div id="map"></div>
Upvotes: 1