Google maps API/Geocoding Uncaught ReferenceError: google is not defined - javascript

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>

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>

Related

Only the last place is getting displayed in the infowindow in google map apis

I am trying to make a single page webapp for displaying markers on a list of places and their corresponding info Windows using knockoutjs. Following is the code.
<head>
<title>Google maps</title>
<link rel=stylesheet type=text/css href='css/style.css'>
</head>
<body>
<div class="container">
<div class="options-box">
<h1>Liverpool Pubs and Bars - Anfield</h1>
<hr>
<div>
<input id="filter-area" type="text" placeholder="Enter your favorite Pub">
<input id="filter-button" type='button' value="Filter">
</div>
<hr>
<div>
<ul data-bind='foreach: allPlaces'>
<li data-bind='text: name'></li>
</ul>
</div>
</div>
<div id='map'></div>
</div>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places,geometry,drawing&key=MYAPIKEY&callback=initMap"
async defer></script>
<script type="text/javascript" src="js/knockout-3.2.0.js"></script>
<script type="text/javascript" src="js/app.js"></script>
</body>
JS code.
var ViewModel = function (googleMap, myPlaces, infoWindow) {
var self = this;
self.map = googleMap;
self.allPlaces = [];
self.markers = [];
myPlaces.forEach(function(place) {
newObj = new Place(place);
title = newObj.name;
console.log(title);
// Getting the geocode for the place.
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ 'address': place.address }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
marker = new google.maps.Marker({
map: self.map,
position: results[0].geometry.location,
animation: google.maps.Animation.DROP,
title: title
});
self.markers.push(marker);
(function (marker, title) {
google.maps.event.addListener(marker, 'click', function (e) {
infoWindow.setContent(title);
infoWindow.open(self.map, marker);
});
})(marker, title);
}
});
self.allPlaces.push(newObj);
});
}
var Place = function(data) {
this.name = data.name;
this.address = data.address;
}
var createMap = function () {
var map;
// Constructor creates a new map - only center and zoom are required.
// Centering map at Anfield.
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 53.4308294, lng: -2.96083},
mapTypeControl: false,
zoom: 13
});
return map;
}
function initMap() {
google.maps.event.addDomListener(window, 'load', function(){
// list of my places.
var myPlaces = [
{
name: 'The Albert',
address: '185 Walton Breck Rd, Liverpool L4 0RE, UK'
},
{
name: 'Arkles',
address: '77 Anfield Rd, Liverpool L4 0TJ, UK'
},
{
name: 'The Sandon',
address: '178-182 Oakfield Rd, Liverpool L4 0UH, UK'
},
{
name: 'The Park Pub',
address: '216-218 Walton Breck Rd, Liverpool L4 0RQ, UK'
},
{
name: 'The Twelfth Man',
address: '121 Walton Breck Rd, Liverpool L4 0RD, UK'
}
];
var googleMap = createMap();
var infoWindow = new google.maps.InfoWindow();
ko.applyBindings(new ViewModel(googleMap, myPlaces, infoWindow))
});
}
function populateInfoWindow(marker, infowindow) {
// Check to make sure the infowindow is not already opened on this marker.
if (infowindow.marker != marker) {
infowindow.marker = marker;
infowindow.setContent('<div>' + marker.title + '</div>');
infowindow.open(map, marker);
// Make sure the marker property is cleared if the infowindow is closed.
infowindow.addListener('closeclick',function(){
infowindow.setMarker = null;
});
}
}
The rest of the map driven code is regular initMap function. The initMap function creates a infowindow, initializes a list of places with name and address attributes. And the google is initialized.
The markers are appearing correctly, though clicking on them opens the info window with only the name of last element. Is it something related to JS closures? How can I implement an IFFE here. Would it solve the issue.
Never mind, added var to the statements newObj and title and the problem was fixed.!!

Placing GoogleMap Markers from PHP/SQL via XML

I'm trying to load a couple of LatLongs from an SQL DB into a Google Maps API on a webpage. I've been following this tutorial, even to the point of copying code straight from it since I'm such a Javascript noob.
What I have so far is:
-Coordinates can be added from the form on the right side of the page (they show up in phpMyAdmin)
-The php script to make an xml of the LatLongs works flawlessly (what do you mean I only get 2 links?)
The problem USED TO BE that the markers wouldn't show up on the map, but the map still loaded. After I tried rewriting the page to better match the code in the tutorial, the map itself won't load. I've read through some other threads on SE related to problems with this tutorial, but nothing in those seems to work...
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBvwCMuLz31gLXoawbDBntieQjGPMrf5vA" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
well: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.000, -115.000),
zoom: 6
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("create_xml.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>";
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
</head>
<body onload="load()">
<div id="map" style="float:left; width:50%;"></div>
Thanks in advance!
Your current problem is your map doesn't have a size. You changed this:
<div id="map" style="width: 500px; height: 300px"></div>
to:
<div id="map" style="float:left; width:50%; height:100%"></div>
For that to work you also need to add additional css:
html, body {
height: 100%;
width: 100%;
}
Proof of concept snippet:
var customIcons = {
well: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(55.000, -115.000),
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infoWindow = new google.maps.InfoWindow();
}
load();
html,
body {
height: 100%;
width: 100%;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3" type="text/javascript"></script>
<div id="map" style="float:left; width:50%; height:100%;"></div>
<div style="float:right; width:50%;">
<h1>WellMap</h1>
<br>
<!-- <img src="well_icon.png"> -->
<br>
<form name="new_well" method="" action="">
Well Name:
<input type="text" name="wellName" id="wellName"/>
<br/>Well Latitude:
<input type="text" name="wellLat" id="wellLat" />
<br/>Well Longitude:
<input type="text" name="wellLong" id="wellLong" />
<br/>
<input type="submit" name="submit" value="Add Well" />
</form>
</div>

MVC4/Razor with Google Maps

i try to show a googlemaps map in my mvc4 partial view. It worked if i hardcode the latitude and longitude in the javascript - but i want to make it more dynamically. So i tried to replace the long and lat with variables. But i only got a grey googlemaps view. Here is my code. What is wrong? Can anyone help me to fix this?
<br />
<div id="map_canvas" style="width: 640px; height: 480px;">
</div>
#{
var lat = 6.9167;
var lng = 79.8473;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
$(document).ready(function () {
initialize();
});
function initialize() {
var mapOptions = {
center: new google.maps.LatLng('#lat', '#lng'),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
Try with:
<br />
<div id="map_canvas" style="width: 640px; height: 480px;">
</div>
#{
var lat = "6.9167";
var lng = "79.8473";
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<script type="text/javascript">
$(document).ready(function () {
initialize();
});
function initialize(lat, lng) {
var mapOptions = {
center: new google.maps.LatLng(#lat, #lng),
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
</script>
Edited
If latitude and longitude values are stored as double into variables or properties, you should pay attention to the string convertion because of the culture format problem.
I think that the best solution is to use the ToString("0.#####", CultureInfo.CreateSpecificCulture("en-GB")) method, as:
var lat = Model.latitude.ToString("0.#####", CultureInfo.CreateSpecificCulture("en-GB"));

Google geocoder does not work

This is my index.html file - The part i'm having trouble with is getting the geocode function to work. The form and button show up but nothing happens when i press the button at all.
<!DOCTYPE html>
<html>
<head>
<title>First Google Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function initialize() {
var latlng = new google.maps.LatLng(43.696299,-79.346271);
var myOptions = {
zoom:13,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var myPlacesKML = new google.maps.KmlLayer('http://mristo.webatu.com/melissaristo/kml/torontodonvalley.kml?ver=1');
myPlacesKML.setMap(map);
function geocode() {
address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
}
</script>
</head>
<body onload="initialize()">
<input type="text" id="address">
<input type="button" onclick="geocode();" value="Geocode it!"
}
</script>
<body onload="initialize()">
<div id="map_canvas" style="width:500px; height:400px"></div>
</body>
</html>
The form and button show up but the the button doesn't do anything when i click it.
Any ideas? I'm very new to this and pretty lost
This code has a lot of bugs in it. I fixed it up. It will place a marker at the address you input in the text box.
<!DOCTYPE html>
<html>
<head>
<title>First Google Map</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map;
function initialize() {
var latlng = new google.maps.LatLng(43.696299,-79.346271);
var myOptions = {
zoom:13,
center: latlng,
mapTypeId: google.maps.MapTypeId.MAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
geocoder = new google.maps.Geocoder();
var myPlacesKML = new google.maps.KmlLayer('http://mristo.webatu.com/melissaristo/kml/torontodonvalley.kml?ver=1');
myPlacesKML.setMap(map);
}
function geocode() {
address = document.getElementById("address").value;
geocoder.geocode({
'address': address,
'partialmatch': true}, geocodeResult);
}
function geocodeResult( 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);
}
}
</script>
</head>
<body onload="initialize()">
<input type="text" id="address">
<input type="button" onclick="geocode();" value="Geocode it!">
<div id="map_canvas" style="width:500px; height:400px"></div>
</body>
</html>
Here are the bugs:
1. extra }
2. map variable was local, needed to be global.
3. missing function geocodeResult
4. extra body tag
5. missing closing > from input
6. move geocode() from inside initialize() to global.

Combining Google Maps Geocoder and Leaflet Map Receiving Error: Invalid LatLng object

I'm using Google Maps Geocoder to grab the latitude and longitude of an address. I'm then taking that address and using Leaflet and panning the map to the latitude + longitude coordinates. However, I'm receiving an error from Firebug saying Error: Invalid LatLng object: (-33.8674869, 151.20699020000006, undefined). I know my variable geolocation returns -33.8674869, 151.20699020000006 but not the undefined. What's causing the problem?
<body onload="initialize()">
<div id="result"></div>
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map"></div>
<script type="text/javascript">
var map = L.map('map').setView([33.7489954, -84.3879824], 13);
var geocoder;
function initialize() {
geocoder = new google.maps.Geocoder();
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var geolocation = String(results[0].geometry.location);
var geolocation = geolocation.replace('(','');
var geolocation = geolocation.replace(')','');
map.panTo([geolocation]);
} else {
$('#result').html('Geocode was not successful for the following reason: ' + status);
}
});
};
L.tileLayer('http://{s}.tile.cloudmade.com/apikeyputhere/997/256/{z}/{x}/{y}.png', {
maxZoom: 18
}).addTo(map);
</script>
Replace this:
var geolocation = String(results[0].geometry.location);
var geolocation = geolocation.replace('(','');
var geolocation = geolocation.replace(')','');
map.panTo([geolocation]);
with that:
map.panTo([results[0].geometry.location.lat(),results[0].geometry.location.lng()]);
Explanation:
You assign a string to the first array-value, it's the same as:
geolocation=new Array('-33.8674869, 151.20699020000006')//contains 1 string
The string will not be evaluated, it will remain 1 string, but you need an array with 2 floats:
geolocation=new Array(-33.8674869, 151.20699020000006)//contains 2 floats
The undefined is the missing 2nd item of the array provided to panTo()

Categories

Resources