This question has been answered before, however when I implement the stated solution it does not work for me. Any guidance would be greatly appreciated:)
function geolocateFunc(){
GMaps.geolocate({
success: function(position) {
map.setCenter(position.coords.latitude,position.coords.longitude);
map.addMarker({
icon: 'http://maps.google.com/mapfiles/ms/icons/blue-dot.png',
scaledSize: new google.maps.Size(150, 150),
lat: position.coords.latitude,
lng: position.coords.longitude,
infoWindow: {content: "<strong>This is my current location</strong>"},
});
},
error: function(error) {
alert('Geolocation failed: '+error.message);
},
not_supported: function() {
alert("Your browser does not support geolocation");
},
always: function() {
alert("Done!");
}
});
}
I tried the scaledSize function and it does not see to work
Try instantiating a new Marker rather than the addMarker method. If still no joy see if the "optimized" attribute setting makes adifference
Courtesy w3schools: -
<!DOCTYPE html>
<html>
<body>
<div id="map" style="width:100%;height:500px"></div>
<script>
function myMap() {
var mapCanvas = document.getElementById("map");
var myCenter = new google.maps.LatLng(51.508742,-0.120850);
var mapOptions = {center: myCenter, zoom: 5};
var map = new google.maps.Map(mapCanvas,mapOptions);
var pinkball = {size: new google.maps.Size(100, 100),
scaledSize: new google.maps.Size(100, 100),
url: "pinkball.png"};
var marker = new google.maps.Marker({
position: myCenter,
icon: pinkball
});
marker.setMap(map);
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBu-916DdpKAjTmJNIgngS6HL_kDIKU0aU&callback=myMap"></script>
<!--
To use this code on your website, get a free API key from Google.
Read more at: https://www.w3schools.com/graphics/google_maps_basic.asp
-->
</body>
</html>
Related
I would like to show a location on google map, but I don't know where is my wrong. not showing any thing :
<div id="map-canvas" style="width:100%; height:300px;">
</div>
.
.
.
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
// Google map
if ($('#map-canvas').length) {
var
GOOGLE_MAP_LAT = 40.7564971,
GOOGLE_MAP_LNG = -73.9743277;
var map,
service;
jQuery(function($) {
$(document).ready(function() {
var latlng = new google.maps.LatLng(GOOGLE_MAP_LAT, GOOGLE_MAP_LNG);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
marker.setMap(map);
$('a[href="#google-map-tab"]').on('shown.bs.tab', function(e) {
google.maps.event.trigger(map, 'resize');
map.setCenter(latlng);
});
});
});
}
</script>
</body>
updated
my console messages :
Using //# to indicate sourceMappingURL pragmas is deprecated. Use //# instead jquery.js:1:0
Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen.[Learn More] <unknown>
SyntaxError: expected expression, got '<' myjs.js:1:0
TypeError: $(...).position(...) is undefined
custom.js:308:20
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
I think you need include jquery library, because you are using $(document).ready(function() .
I have updated your code by adding jquery library. Please try the below code , hope it will work.
<div id="map-canvas" style="width:100%; height:300px;">
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
// Google map
if ($('#map-canvas').length) {
var
GOOGLE_MAP_LAT = 40.7564971,
GOOGLE_MAP_LNG = -73.9743277;
var map,
service;
jQuery(function($) {
$(document).ready(function() {
var latlng = new google.maps.LatLng(GOOGLE_MAP_LAT, GOOGLE_MAP_LNG);
var myOptions = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var marker = new google.maps.Marker({
position: latlng,
map: map
});
marker.setMap(map);
$('a[href="#google-map-tab"]').on('shown.bs.tab', function(e) {
google.maps.event.trigger(map, 'resize');
map.setCenter(latlng);
});
});
});
}
</script>
I am currently trying to add geolocation functionality to the following code:
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var marker;
var infowindow;
function initialize() {
var latlng = new google.maps.LatLng(51.507059, -0.122631);
var options = {
zoom: 14,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), options);
var html = "<table/>" +
"<tr><td>Name:</td><td><input id='name' type='text'/></td></tr>" +
"<tr><td><br/>Description:</td><td><input id='description' type='text'/></td></tr>" +
"<tr><td/><td><br/><center><input onclick='saveData()' type='button' value='Save & Close'/></center></td></tr>";
infowindow = new google.maps.InfoWindow({
content: html
});
google.maps.event.addListener(map, "click", function(event) {
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
google.maps.event.addListener(marker, "click", function() {
infowindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Geolocation Code:
// 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: Locations services failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(51.507059, -0.122631),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
However, when I attempt to merge the initialize functions, I get the error 'Cannot read property '_e3' of undefined.' If I keep the functions separate, the program simply ignores the geolocation code. So, I'm stuck, and was hoping someone could give me a hand. Thanks a million!
Note: I have tried everything relevant at https://developers.google.com/maps/, and have checked through all of the very similar questions on this site - this is not a duplicate post. Also, please ignore my use of HTML character codes inside the JavaScript - it's the only way to get HTML (infowindow) inside JavaScript (code) inside HTML (webdata) working.
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);
The map is loaded correctly without marker object ,But it doesn't load when I add Marker object on this structure here my
<!doctype html>
<html>
<head>
<script type="text/javascript"
src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script src="jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="script.js" type="text/javascript"></script>
<script type="text/javascript">
$.geolocation.find(function(location) {
var lat = location.latitude;
var lng = location.longitude;
var map = new google.maps.Map($('#mapDiv').get(0), {
center: new google.maps.LatLng(lat, lng),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var pinColor = "FE7569";
var pinImage = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2" + pinColor,
new google.maps.Size(21, 34),
new google.maps.Point(0,0),
new google.maps.Point(10, 34));
var pinShadow = new google.maps.MarkerImage("http://chart.apis.google.com/chart?chst=d_map_pin_shadow",
new google.maps.Size(40, 37),
new google.maps.Point(0, 0),
new google.maps.Point(12, 35))
var marker= new google.maps.Marker({
position: new google.maps.LatLng(lat, lng),
map: map,
icon: pinImage,
shadow: pinShadow
});
});
</script>
</head>
<body>
<div id="mapDiv" style="width:700px; height: 500px;"></div>
</body>
</html>
The script which is included in the page script.js
(function($){
$.extend($.support,{
geolocation:function(){
return $.geolocation.support();
}
});
$.geolocation = {
find:function(success, error, options){
if($.geolocation.support()){
options = $.extend({highAccuracy: true, track: false}, options);
($.geolocation.object())[(options.track ? 'watchPosition' : 'getCurrentPosition')](function(location){
success(location.coords);
}, function(){
error();
}, {enableHighAccuracy: options.highAccuracy});
}else{
error();
}
},
object:function(){
return navigator.geolocation;
},
support:function(){
return ($.geolocation.object()) ? true : false;
}
};
})(jQuery);
I need to include the marker with the google map
another issue that this code is running only on Firefox and IE ,but it doesn't run on Google Chrome
Take a look at this, I think this is solved, your error was in the url parameters and now it is working in Chrome too. You can also change the color of your marker by replacing FE7569 according to your needs.
Eg: 73B5EB or 33DE61
Another thing you can do is to put a text in the marker like this:
http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=You%20are%20here|FE7569
Eg:
Live demo of your code but corrected:
http://jsfiddle.net/oscarj24/sPsxh/
Hope this helps :-)
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>