What is the global object in a Google Maps app?
I rewrote the js at https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
in coffeescript, which generated the following javascript:
// Generated by CoffeeScript 1.6.3
(function() {
var errorFlag, initialize;
google.maps.visualRefresh = true;
initialize = function() {
var map, mapOptions;
mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
if (navigator.geolocation) {
return navigator.geolocation.getCurrentPosition(function(position) {
var infowindow, pos;
pos = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found'
});
return map.setCenter(pos);
}, function() {
return handleNoGeolocation(true);
});
} else {
return handleNoGeolocation(false);
}
};
handleNoGeolocation(errorFlag = function() {
var content, infowindow, options;
if (errorFlag) {
content = 'Geolocation failed';
} else {
content = 'Your browser does not support Geolocation';
}
options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
infowindow = new google.maps.InfoWindow(options);
return map.setCenter(options.position);
});
google.maps.event.addDomListener(window, 'load', initialize);
}).call(this);
The app works when I use the js from their website, but not when I use the js generated by coffeescript. My guess is that since the map variable is a global variable in their code, I should bind it to the global object as well. I tried window.map, but that didn't work either. Any ideas?
The handleNoGeolocation function defination is wrongly compiled. It should have been
var errorFlag, initialize, handleNoGeolocation;
//..
//..
handleNoGeolocation = function (errorFlag) {
//..
//..
};
rather than
handleNoGeolocation(errorFlag = function() {
//..
//..
});
I guess something went wrong with indentation.
hope this helps.
Related
I have separate file of JavaScript and HTML and I want to revert the button to his function in JavaScript file using jQuery $('#') then I want to send the value of lat and lon to the database.
https://jsfiddle.net/razanrab/qct5j19z/6/
var map, infoWindow;
var geocoder;
function initMap() {
geocoder = new google.maps.Geocoder();
map = new google.maps.Map(document.getElementById('mapCanvas'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var marker = new google.maps.Marker({
position: pos,
map: map,
draggable: true,
title: 'Your position'
});
/*infoWindow.setPosition(pos);
infoWindow.setContent('Your position');
marker.addListener('click', function() {
infoWindow.open(map, marker);
});
infoWindow.open(map, marker);*/
map.setCenter(pos);
updateMarkerPosition(marker.getPosition());
geocodePosition(pos);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
map.panTo(marker.getPosition());
});
google.maps.event.addListener(map, 'click', function(e) {
updateMarkerPosition(e.latLng);
geocodePosition(marker.getPosition());
marker.setPosition(e.latLng);
map.panTo(marker.getPosition());
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
You said you wanted to do this with jQuery?
Add this function to the bottom of your map JS file:
$("#locate").click(function(){
initMap();
});
You can then delete the onClick="" attribute on the button.
Here's the updated working JSFiddle: https://jsfiddle.net/qct5j19z/7/
(You will need jQuery included above on your webpage. See here)
Based on your comment above im guessing that you had the js and the html in the same file and it worked but you moved the javascript to a seperate file and now it no longer works
make sure your adding this
<script src="path/to/file.js"></script>
Since web browsers cache js files whenever you update the javascript file try versioning like this
<script src="path/to/file.js?v=0.0.1"></script>
That way all users will recieve the updated file
I'm having a problem with figuring out how to make a function run - and then wait for user input (I.E: If user selects to share location), and then run another function. When the "getUserLocation" function runs, the "addLocationArrayToMap" function runs before the user has a chance to make any input on the alert window.
Some debugging returns "userPos is not defined" which makes me think that my guess as to why it's not working is accurate..?
Code below:
var markers =[];
var myLocationIconArray = [];
var infoWindowContentString = '';
var addInfowindow;
var distanceArray = [];
var addInfowindow;
function runAll() {
getUserLocation(addLocationArrayToMap);
}
function getUserLocation() {
map.setOptions({draggable: true, zoomControl: true, scrollwheel: true, disableDoubleClickZoom: false});
// Another function that deletes 'dummy' markers before adding Real Markers to the map
deleteMarkers();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
centerPos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
map.setCenter(centerPos);
addMarker(centerPos);
}, function() {
handleLocationError(true, map.getCenter());
});
} else {
//Browser doesn't support Geolocation
handleLocationError(false, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, defaultPos) {
infoWindowContentString = "Sorry, we can't get your location.";
addInfowindow = new google.maps.InfoWindow({
content: infoWindowContentString
});
map.setCenter(defaultPos);
addMarker(defaultPos, addInfowindow);
}
function addMarker(location, addInfowindow) {
var marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
icon: yourLocation,
draggable: false,
clickable: true
});
if (addInfowindow == null) {
var myLocationInfowindow = new google.maps.InfoWindow({
content: "Your location"
});
myLocationInfowindow.open(map, marker);
myLocationIconArray.push(marker);
} else {
myLocationIconArray.push(marker);
}
}
function addLocationArrayToMap() {
userPos = new google.maps.LatLng(centerPos.lat, centerPos.lng);
for (var z = 0; z < dabblersArray.length; z++) {
// dabblersArray is an array of Lat & Lng coords.
dabblerLocation = new google.maps.LatLng(dabblersArray[z].lat, dabblersArray[z].lng);
calculateDistance(userPos, dabblerLocation);
markers.push(new google.maps.Marker({
position: dabblersArray[z],
map: map,
icon: dabblers,
draggable: false,
clickable: true
}));
// Some logic to add the distance from the user and the dabblersArray as an alert window above each marker - haven't done this yet.
}
}
function calculateDistance(userPos, dabblerLocation) {
distance = google.maps.geometry.spherical.computeDistanceBetween(userPos, dabblerLocation);
distanceArray.push(distance);
}
JavaScript has no concept of making a user wait. The way to accomplish this is using callbacks, exactly like navigator.geolocation.getCurrentPosition exemplifies. It has success and error callbacks, which you are already using.
And you're already passing in addLocationArrayToMap to getUserLocation, but not using it. It should be invoked as a callback function in the navigator.geolocation.getCurrentPosition success handler. Mission accomplished.
function runAll() {
getUserLocation(addLocationArrayToMap);
}
function getUserLocation(onComplete) {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
//Your logic...
//Invoke callback
onComplete();
}, function() {
handleLocationError(true, map.getCenter());
});
}
}
I have integrate a Google map in my website but map is not load in my website.But when I open inspect element map will work when I close inspect element map will disappear automatically.I don't know why its going like this,Please let me know what the problem. Here is my map code
Thanks in Advance
<div id="mapCanvas" style="width:100%; height:400px"></div>
<input type="text" title="Latitude" id="latt_val">
<input type="text" title="Longitude" id="long_val">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
document.getElementById("latt_val").value = latLng.lat();
document.getElementById("long_val").value = latLng.lng();
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(15.486432009100538, 73.82759375);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 12,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
google.maps.event.trigger(window,'resize',{});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
[UPDATE]
Hey, I'm still really curious what's going on here. Do you happen to have an AdBlocker enabled on your browser that might prevent the map from loading? Have you checked if this works in multiple browsers?
I made a codepen of our problem: http://codepen.io/trevorwhealy/pen/obRQdW.
And your map is working perfectly fine. If, on-load of this pen, you still do not see something, then I think we can safely say this is a browser issue.
[OLD POST]
Try putting your code:
google.maps.event.trigger(window,'resize',{}); // or trigger(map
after
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
but still within your initialize function.
I have one istance of a google map on a page. I'm using the following line of code to get the map and assign it to a new variable.
newmap = map.getMap();
When I print newmap to console it shows that the map is being assigned to the variable. I now want to duplicate that map with the exact same options into the following div....
<div id="map-larger-canvas"></div>
Any idea's how I would do this?
Define option for every map and after init twice:
var map_options = {
center: new google.maps.LatLng(41.811729,12.738513),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
function initialize() {
var map1 = document.getElementById('map-1st');
var map_canvas = document.getElementById('map-larger-canvas');
var map1 = new google.maps.Map(map1, map_options)
var map2 = new google.maps.Map(map_canvas, map_options);
}
google.maps.event.addDomListener(window, 'load', initialize);
I use Json in this way, take a look:
$('#map_canvas_europe').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'json/locations_europe.json', function(data) {
$.each( data.markers, function(i, marker) {
$('#map_canvas_europe').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map_canvas_europe').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
$('#map_canvas_asia').gmap().bind('init', function() {
// This URL won't work on your localhost, so you need to change it
// see http://en.wikipedia.org/wiki/Same_origin_policy
$.getJSON( 'json/locations_asia.json', function(data) {
$.each( data.markers, function(i, marker) {
$('#map_canvas_asia').gmap('addMarker', {
'position': new google.maps.LatLng(marker.latitude, marker.longitude),
'bounds': true
}).click(function() {
$('#map_canvas_asia').gmap('openInfoWindow', { 'content': marker.content }, this);
});
});
});
});
When I load this page into a div (using jQuery.load()), marker icon is not showed. The icon will show after reloaded the page. Is that caused map not initialized when i pass it into placeMarker function? How to solve it.
<script type="text/javascript">
var map;
var markers = new Array();
var marker;
var infoWindow = new google.maps.InfoWindow();
function initialize() {
var myLatlng = new google.maps.LatLng(-6.19605333333333,106.79684);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
fillPositionForm(event.latLng);
});
}
function placeMarker(location) {
if ( marker ) {
marker.setPosition(location);
} else {
marker = new google.maps.Marker({
position: location,
map: map,
animation: google.maps.Animation.DROP,
draggable: true
});
}
google.maps.event.addListener(marker, 'dragend', function(event) {
clearOverlays();
fillPositionForm(event.latLng);
});
}
function fillPositionForm(location){
jQuery("#latitude").val(location.lat());
jQuery("#longitude").val(location.lng());
}
function clearOverlays() {
if (markers) {
for (i in markers) {
markers[i].setMap(null);
}
}
}
jQuery(document).ready(function() {
initialize();
jQuery("#frmAddPoi").validate({
messages: {
latitude: "Please click on map to select poi center position",
longitude: "Please click on map to select poi center position",
},
submitHandler: function(form) {
return postForm(form, "savepoi", "listcustopoi", false, false);
}
});
});
</script>
<div id="map_canvas" class="widgettitle" style="height:240px;"></div>
You are attaching placeMarker to map.click event listener.
google.maps.event.addListener(map, 'click', function(event) {
placeMarker(event.latLng);
fillPositionForm(event.latLng);
});
You need to load it after map is called.
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
placeMarker(myLatlng);
See jsFiddle
You should have your function Initialize() called after your load() success. It's better to have your javascript in your main page, not in the page loaded.
Or you can use an iFrame, the easiest way.