I can't seem to add a markers to my maps. I am using Google Maps v.3 and Ruby on Rails.
Here's my JavaScript:
<script type="text/javascript">
var map;
function initialize()
{
var lat, lon, myOptions;
if(navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(function(position)
{
lat = position.coords.latitude;
lon = position.coords.longitude;
myOptions = {
center: new google.maps.LatLng(lat, lon),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
},
function(error)
{
alert('Error: An error occur while fetching information from the Google API');
});
}
else
{
alert("Your browser doesn't support geolocations, please consider downloading Google Chrome");
}
}
// Function for adding a marker to the page.
function addMarker(lat, lng) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map
});
}
</script>
Here is the HTML page and how I call it:
<div id="maps">
<div id="map_canvas" style="width:100%; height:400px">
</div>
<script type="text/javascript">
initialize();
addMarker(46.4352,-80.9455);
</script>
It's because addMarker() is being called before initialize() has finished.
initialize() needs to wait for a response from the geolocation api which means the map isn't initialized when you try and create the marker.
If you wrap addMarker inside callback and pass that to the initializing function which calls the callback function once a response is received then it should work as expected.
initialize(function() {
addMarker(46.4352,-80.9455);
});
function initilize(callback) {
navigator.geolocation.getCurrentPosition(function(position) {
// set up the map
callback();
});
}
Related
I have this script to display markers on a google map, which works great but now I want to get current position to zoom in on map initially..
<body onload="initCoords()">
function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
} // this gets the current location loaded when body loads //
How do I pass the lat and long into the map?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(lat, long),
zoom: 12
});
</body>
It throws lat and long are not defined.
In the callback showPosition call the setPosition method of the map. As you have declared map within the initMap function perhaps declare the other functions also within the body of initMap
function initMap() {
lat=56;
long=-2;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(lat, long),
zoom: 12
});
var initCoords=function() {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
var showError=function(e){
alert(e)
};
var showPosition=function( position ) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latlng=new google.maps.LatLng(lat,long);
map.setPosition( latlng );
/* add marker?? */
}
/* other code ?.... */
}/* close function*/
Or, declare use the callback function to initialise the map
var map,lat,long;
function initMap() {
var initCoords=function() {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
var showError=function(e){
alert(e)
};
var showPosition=function( position ) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latlng=new google.maps.LatLng(lat,long);
var map = new google.maps.Map( document.getElementById('map'), {
center: latlng,
zoom: 12
});
}
/* other code ?.... */
}/* close function*/
If you are loading the Google Maps JS API script asynchronously like so:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
then the body onload event will occur and call initCoords() before the maps API has fully been loaded. This means that any code inside that function that is trying to access the maps API will not work.
One option is to listen to the tilesloaded event of the map object and run the zoom-in function when that event is fired the first time (which happens when the visible tiles have finished loading).
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40, lng: 20},
zoom: 3
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
map.setZoom(8); // call initCoords()
});
}
I use addListenerOnce so that the map zooms in only after the first time the map's tiles have finished loading.
Here is a JSBin with this functionality.
I use a google map with javaScript and my code is :
<script type="text/javascript">
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(-12.043333,-77.028333);
var myOptions = {
zoom: 17,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById('map_canvas'),
myOptions);
google.maps.event.addListener(map, "mousedown", function (e) {
//lat and lng is available in e object
var latLng = e.latLng;
console.log(latLng);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>`
The result of e.latLng is an empty object.
I tried to click the event, but the result is empty.
What should I do or change?
Your code is working fine :
Click on map and your coordinates will come in alert
Please check here
I am trying to check if user location / Google marker inside the KML layer or not.
Is there any event of KML to determine this?
Or I can check after marker placed on the google map?
Any idea?
My sample code is here.
is there any suggestion or sample code?
Waiting for your kind response.
Thanks in advance.
var map;
function initialize() {
var chicago = new google.maps.LatLng(49.051078, -122.314221);
var mapOptions = {
zoom: 11,
center: chicago
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://aeronnovation.ae/NoFlyZoneFile/doc.kml',
preserveViewport: true
});
ctaLayer.setMap(map);
if (navigator.geolocation) {
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,
content: 'You are here'
});
map.setCenter(pos);
}, function () {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
KmlLayer doesn't allow access to the underlying polygon data. You can do it with FusionTables (if you import your KML data) or a third party KML parser (like geoxml3 or geoxml-v3)
example using geoxml3
example using FusionTables
example using geoxml3 with your data through a proxy
Hi all I have the following code:
var map;
var infowindow;
function getLocation()
{
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(initialize);
}
else{x.innerHTML="Geolocation is not supported by this browser.";}
}
function initialize(position) {
var pyrmont = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map = new google.maps.Map(document.getElementById('map'), {
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: pyrmont,
zoom: 15
});
var request = {
location: pyrmont,
radius: 500,
types: ['restaurant']
};
...
Basically I can get the map to work great if I set the Long/Lat co-ordinates but instead I want these to be passed by getting the users location. With the code above the map is displaying on my phone but with the following error:
TypeError: 'undefined' is not an object (evaluating 'position.coords.latitude')
but on the desktop I get no map and the following error:
Uncaught TypeError: Cannot read property 'latitude' of undefined
Any help would be great I'm a newbie to Javascript and these APis
Later in your code, on your page at http://markhaynes.me/mwp/addloc.html, you're calling google.maps.event.addDomListener(window, 'load', initialize);
This causes Google to call the initialize() function, but it passes an event object as the position parameter instead of the position object you expected.
Well it's not an issue with the geolocation API. Here's a JSFIDDLE of geolocation: http://jsfiddle.net/w4nvZ/3/
There's also the documentation and examples for the API here: http://www.w3schools.com/html/html5_geolocation.asp
Google even has an example of geolocation working with the JavaScript Google Maps API: https://google-developers.appspot.com/maps/documentation/javascript/examples/map-geolocation
var map;
function initialize() {
var mapOptions = {
zoom: 6,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
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,
content: 'Location found using HTML5.'
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
I am writing JavaScript code using Google Maps API.
map = new google.maps.Map2(document.getElementById("map_canvas"));
map.setCenter(new google.maps.LatLng(37.4419, -122.1419), 13);
The above code sets the default location of the map canvas to Palo Alto.
How can we write the script in such a way that the setCenter function automatically points to the current location of the client?
You can use the HTML5 GeoLocation API in browsers that support it.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('geolocation not supported');
}
function success(position) {
alert(position.coords.latitude + ', ' + position.coords.longitude);
}
function error(msg) {
alert('error: ' + msg);
}
I can think of two possible options.
First you may want to consider using the GeoLocation API as ceejayoz suggested. This is very easy to implement, and it is a fully client-side solution. To center the map using GeoLocation, simply use:
map.setCenter(new google.maps.LatLng(position.coords.latitude,
position.coords.longitude), 13);
... inside the success() callback of the GeoLocation's getCurrentPosition() method.
Unfortunately only a few modern browsers are currently supporting the GeoLocation API. Therefore you can also consider using a server-side solution to resolve the IP address of the client into the user's location, using a service such as MaxMind's GeoLite City. Then you can simply geocode the city and country of the user inside the browser, using the Google Maps API. The following could be a brief example:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Google Maps API Geocoding Demo</title>
<script src="http://maps.google.com/maps?file=api&v=2&sensor=false"
type="text/javascript"></script>
</head>
<body onunload="GUnload()">
<div id="map_canvas" style="width: 400px; height: 300px"></div>
<script type="text/javascript">
var userLocation = 'London, UK';
if (GBrowserIsCompatible()) {
var geocoder = new GClientGeocoder();
geocoder.getLocations(userLocation, function (locations) {
if (locations.Placemark) {
var north = locations.Placemark[0].ExtendedData.LatLonBox.north;
var south = locations.Placemark[0].ExtendedData.LatLonBox.south;
var east = locations.Placemark[0].ExtendedData.LatLonBox.east;
var west = locations.Placemark[0].ExtendedData.LatLonBox.west;
var bounds = new GLatLngBounds(new GLatLng(south, west),
new GLatLng(north, east));
var map = new GMap2(document.getElementById("map_canvas"));
map.setCenter(bounds.getCenter(), map.getBoundsZoomLevel(bounds));
map.addOverlay(new GMarker(bounds.getCenter()));
}
});
}
</script>
</body>
</html>
Simply replace userLocation = 'London, UK' with the server-side resolved address. The following is a screenshot from the above example:
You can remove the marker by getting rid of the map.addOverlay(new GMarker(bounds.getCenter())); line.
that already exists in the google api:
if (GBrowserIsCompatible())
{
var map = new google.maps.Map2(document.getElementById("mapdiv"));
if (google.loader.ClientLocation)
{
var center = new google.maps.LatLng(
google.loader.ClientLocation.latitude,
google.loader.ClientLocation.longitude
);
var zoom = 8;
map.setCenter(center, zoom);
}
}
There are several threads with the same question...
This solution tries to get user location from browser first,
if the user refused or any other error occurs it then gets the location from user's IP address
mapUserLocation = () => {
navigator.geolocation
? navigator.geolocation.getCurrentPosition(
handlePosition,
getLocationFromIP
)
: getLocationFromIP();
};
getLocationFromIP = () => {
fetch("http://ip-api.com/json")
.then(response => response.json())
.then(data => {
data.lat &&
data.lon &&
updateUserPosition({
lat: data.lat,
lng: data.lon
});
})
.catch(error => {
console.log(`Request failed: `, error);
});
};
handlePosition = position => {
const userPos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
updateUserPosition(userPos);
};
updateUserPosition = position => {
map.setCenter(position, 13);
};
and call it like:
mapUserLocation();
An updated version of #ceejayoz's answer:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('geolocation not supported');
}
function error(msg) {
alert('error: ' + msg);
}
function success(position) {
var myLatlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
zoom: 12,
center: myLatlng,
scaleControl: false,
draggable: false,
scrollwheel: false,
navigationControl: false,
mapTypeControl: false
}
map = new google.maps.Map(document.getElementsByClassName('map-canvas')[0], mapOptions);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Main map',
icon: iconBase + 'arrow.png'
});
}
map = new google.maps.Map2(document.getElementById("map_canvas"));
pos = new google.maps.LatLng(37.4419, -122.1419);
map.setCenter(pos, 13);
map.panTo(pos);
Try this bro : I centered Indonesia using lat and lng.
$(document).ready(function () {
var mapOptions = {
zoom: 4,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map'), mapOptions);
var center = new google.maps.LatLng(-2.548926, 118.0148634);
map.setCenter(center,4);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<div id="map" style="width:600px; height:450px"></div>