I am trying to create a map with different locations and I am using knockout binding to display some features on my html view.
I have a function that enables me to create various locations.
I want each location to have its own marker. When rendering the map, I display some defaults locations. But I have this error: Uncaught ReferenceError: google is not defined
Here is my code.
defaultMarkers =[
new Locations("Ike's Food & Cocktails","(612) 746-4537","50 S 6th St","",44.97818705436708,-93.27229499816895),
new Locations("Eli's East Food & Cocktails","(612) 331-0031","815 E Hennepin Ave","#",44.99128282822349,-93.24738264083862),
new Locations("Midnord Empanada Food truck","unavailable","unavailable","#",44.97596890779807,-93.27159452192403),
new Locations("Maruso Street Food Bar","(612) 333-0100", "715 E Hennepin Ave","#",44.97760063074655,-93.2754345812601),
new Locations("The House Of Hunger Food Truck","unavailable","unavailable","#",44.97611524414878,-93.27146677068872)];
var map;
function initMap() {
var mapOptions = {
center: {lat: 38.9165087, lng: -77.2482606},
zoom: 13
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
// add defaults markers on map
updateMap(map, defaultMarkers);
}
function Locations(name, contact, fulladress, url, lat, lng){
var self = this;
self.name= name;
self.contact = contact;
self.url = url;
self.fulladress = fulladress;
self.lat = lat;
self.lng = lng;
self.showMe = ko.observable(true);
self.marker = new google.maps.Marker({ // HERE IS THE LINE WHERE THE ERROR OCCUR
position: new google.maps.LatLng(lat, lng),
map: map,
});}
function MapViewModel() {
var self = this;
self.listVenues = ko.observableArray(defaultMarkers);
}
Can you help me figure out where I am doing wrong?
.
Make sure your script is:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&key=APIKEY"></script>
Not including the type="text/javascript" may be messing you up.
Related
So I'm trying to use a combination of Google Autocomplete with Google Maps API V3.
A user will enter an address into an address field (page1), click 'Next', and then a lightbox (page2) will appear with the Map of the address that they entered.
So what will happen is that the lat + long (from page1) of the address will being passed into the lightbox URL (page2) as query params. The script below will need to build itself on page-load, using the lat+long.
Below is the default Google Maps
<script>
function initMap() {
var address = {lat: lat_address, lng: lng_address};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: address
});
var marker = new google.maps.Marker({
position: address,
map: map
});
}
</script>
What I'm unsure about is how to build a script on page-load. Could anyone advise please? Thank you!
Actually I just solved this utilizing the function getQueryVariable to get the value of each query param from the URL, and then using it in the initMap to pass variables on page-load.
<script>
//Function that allows easy access to param->value
function getQueryVariable(variable)
{
var query = window.location.search.substring(1);
var vars = query.split("&");
for (var i=0;i<vars.length;i++) {
var pair = vars[i].split("=");
if(pair[0] == variable){return pair[1];}
}
return(false);
}
//Initialize the GMap
function initMap() {
var latAddress = getQueryVariable('lat_address');
var latAddress = parseInt(latAddress);
var lngAddress = getQueryVariable('lng_address');
var lngAddress = parseInt(lngAddress);
var address = {lat: latAddress, lng: lngAddress};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: address
});
var marker = new google.maps.Marker({
position: address,
map: map
});
}
</script>
I am trying to integrate Google Maps into a WebBrowserControl in my C# WPF program. The map loads in the control and centers on the correct latitude and longitude, however I am having a couple of errors. First of all, the map loads and after a couple of seconds I get an error box appear;
Secondly, when I am trying to add a marker on the location of the latitude and longitude, I get an error even before the map loads at all. Here is my code so far;
mapWebBrowser.NavigateToString(#"<html xmlns=""http://www.w3.org/1999/xhtml"" xmlns:v=""urn:schemas-microsoft-com:vml"">
<head>
<meta http - equiv = ""X-UA-Compatible"" content = ""IE=edge""/>
<meta name = ""viewport"" content = ""initial-scale=1.0, user-scalable=no""/>
<script type = ""text/javascript""
src = ""http://maps.google.com.mx/maps/api/js?sensor=true&language=""es"" ></script>
<script src = 'http://google-maps-utility-library-v3.googlecode.com/svn/trunk/markerclusterer/src/markerclusterer.js'>
</script><script type = ""text/javascript"">
function initialize() {
var latlng = new google.maps.LatLng(" + latitude + ", " + longitude + #");
var myOptions = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById(""map_canvas""), myOptions);
}
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
</script>
</head>
<body onload = ""initialize()"" >
<div id=""map_canvas"" style=""width:100%; height:100%""></div>
</body>
</html>");
This is the function I am attempting to use to add a marker onto the map;
function addMarker( Lat, Long) {
var latLng = new google.maps.LatLng(Lat, Long);
marker = new google.maps.Marker({
position: latLng,
draggable: false,
animation: google.maps.Animation.DROP,
});
markers.push(marker);
var markerCluster = new MarkerClusterer(map, markers)
}
Which I call in C#;
mapWebBrowser.InvokeScript("addMarker", new object[] { latitude, longitude } );
Unfortunately as I stated before both methods are causing issues.
I believe there was a change in Google's APIs back in June and they now require authentication for google maps. I don't see your API key being supplied anywhere. I would suggest you try your HTML/javascript in the browser or where you can sniff the requests and the responses and see what's going on.
If you still can't solve your problem. You may use Script Errors Suppressed too. Then this window will disappear.
webBrowser1.ScriptErrorsSuppressed = true;
I am learning to use javascript right now with Rails and I'm having some issues with updating my markers according to my current position using AJAX. I believe the ready page:load is not running the updated coords that have been attached as a data-attribute, coords since the page is not technically reloading. How can I use my current position data and update it with events with longitude/latitude values?
var map;
$(document).on('ready page:load', function() {
if ("geolocation" in navigator) {
myMap.init();
var coords = $('#map-canvas').data('coords');
if (coords){
myMap.addMarkers(coords);
}
}
});
myMap.init = function() {
if(navigator.geolocation){
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
navigator.geolocation.getCurrentPosition(function(position){
var pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var infoWindow = new google.maps.InfoWindow({
map: map,
position: pos
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
map.setCenter(pos);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url:"/all_events",
method: "GET",
data: {
latitude: latitude,
longitude: longitude
},
dataType: 'script'
});
});
} else {
document.getElementById('map-canvas').innerHTML = 'No Geolocation Support.';
}
};
myMap.addMarkers = function(coords){
var image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
coords.forEach(function(coord){
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(coord.latitude, coord.longitude),
map: map,
icon: image
});
});
}
In order to make your script work in the way you want please try out the following steps:
Put your foreach loop in a function and call it at the end of your successive AJAX callbacks.
Load the AJAX once the Google Maps have finished loading completely. If Google Maps library has not finished loading than you wont be able to create a Google LatLng object, this is what is probably happening over here.
Hope this would help
I spent a lot of time to solve this, and can't figure it how to work, so here is my base:
<script>
function initialize() {
var mapOptions = {
center: new google.maps.LatLng("43.2697,26.9165"),
zoom: 8 };
var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
var marker=new google.maps.LatLng("43.2697,26.9165");
var main=new google.maps.Marker({position:marker});
main.setMap(map);
}
function moveMarker(lat,lng) {
var latlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
//???????
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Now - in HTML i have a button and two text fields. When button is clicked, it fire moveMarker function and pass new latitude and longitude - entered in fields. The goal is that marker must move to new position, and map must be centered - accordingly. I've tryed a lot of hints, but - cant access marker object(with name Main in my case) in order to move it to new position.
Your marker ("main") is local to your initialize file. To access it from an HTML click event, it needs to be in the global scope.
<script>
var main = null;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng("43.2697,26.9165"),
zoom: 8 };
var map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
var marker=new google.maps.LatLng("43.2697,26.9165");
main=new google.maps.Marker({position:marker});
main.setMap(map);
}
function moveMarker(lat,lng) {
var latlng = new google.maps.LatLng(parseFloat(lat), parseFloat(lng));
main.setPosition(latlng);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I've been following the official documentation on how to add markers on the map so far
Nevertheless, I can see only one marker at a time max. If I try to add another one, then it doesn't work (I can't even see the first one).
My process is the following:
I initialize gmaps api:
jQuery(window).ready(function(){
//If we click on Find me Lakes
jQuery("#btnInit").click(initiate_geolocation);
});
function initiate_geolocation() {
if (navigator.geolocation)
{
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "https://maps.googleapis.com/maps/api/js?key=AIzaSyBbfJJVh0jL1X9b7XFDcPuV7nHD1HlfsKs&sensor=true&callback=initialize";
document.body.appendChild(script);
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}
else
{
yqlgeo.get('visitor', normalize_yql_response);
}
}
Then, I display it on the appropriate div. But when it comes to make the AJAX call, in order to get my locations of the different markers I'd like to display, It just doesn't work properly. Here is the code with a simple map displayed (since that's the only thing working for me so far).
function handle_geolocation_query(position){
var mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
alert('Lat: ' + position.coords.latitude + ' ' +
'Lon: ' + position.coords.longitude);
$('#map-canvas').slideToggle('slow', function(){
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
$.when( getLakes(position.coords.latitude, position.coords.longitude)).done(function(results) {
// InitializeGoogleMaps(results);
if(results)
var data = results.map(function (lake) {
//Check if the lake has any open swims, if not, the button will not be clickable and an alert will pop up
if (lake.available>0)
clickable=true;
else
clickable=false;
return {
name: lake.name,
fishs: lake.fisheryType,
swims: lake.swims,
dist: lake.distance,
lat: lake.latitude,
long: lake.longitude,
id: lake.id,
avail: lake.available,
clickable: clickable,
route: Routing.generate('lake_display', { id: lake.id, lat: position.coords.latitude, lng: position.coords.longitude})
}
});
var template = Handlebars.compile( $('#template').html() );
$('#list').append( template(data) );
} );
};
So I'd like to add markers after the AJAX call. I've set up a function that I should call in the when()
function InitializeGoogleMaps(results) {
};
to display the markers in a foreach loop but nope, can't make it work. It looks like this :
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
marker = new google.maps.Marker({
position: location,
map: map
});
Any help would be great !
Thanks
The main issue is that the map variable is declared only in the scope of the anonymous callback on slideToggle. First of all declare at the top-level function scope.
function handle_geolocation_query(position){
var map,
mapOptions = {
zoom: 14,
center: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
mapTypeId: google.maps.MapTypeId.SATELLITE
}
...
Then change the slideToggle callback to initialise the variable instead of redeclaring:
$('#map-canvas').slideToggle('slow', function(){
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
});
Then you should pass map as a second parameter to your InitializeGoogleMaps function and call it using InitializeGoogleMaps(results, map). See where this gets you and hit me back with any questions.