So I'm trying to set up a website for a school project and part of it requires obtaining user location and displaying it on a map. I've managed to get the user location using the geolocator api but can't seem to update the marker as even after getting new lat long it remains in the default location. Any help would be greatly appreciated :)
I've taken a default location (California) to display on loading the website (which it does successfully) and managed to get user location (verified using console to display results) but the code still displays the California marker.
<script type="text/javascript">
var latitude = 36.8;
var longitude = -119.4;
var currloc;
function getLoc() {
if ("geolocation" in navigator) {
navigator.geolocation.getCurrentPosition(function(position) {
latitude = (Math.round(position.coords.latitude*100))/100;
longitude = (Math.round(position.coords.longitude*100))/100;
currloc = {lat: latitude, lng: longitude};
console.log("Geolocation supported");
console.log(latitude);
console.log(longitude);
});
}
else {
latitude = 0.0;
longitude = 0.0;
console.log("Geolocation not supported");
}
}
function mapInit() {
currloc = {lat: latitude, lng: longitude};
var map = new google.maps.Map(document.getElementById("map"), {zoom: 4, center: currloc, disableDoubleClickZoom: true,});
var mark = new google.maps.Marker({
position: currloc,
map: map,
title: latitude+', '+longitude
});
}
</script>
I would expect the marker to change as the initMap function's currloc values have changed however on the map it doesn't show the new location.
getLoc() is asynchronous. Currloc changes after the callback is called. I am assuming you called mapInit synchronously.
Call the marker inside the callback
Related
I want to use an image(.jpg) that I have as a marker instead of the default marker/pin on my Google map. But the image won't show. There are lots of the same questions on this forum but none of them has helped me.
As soon as I take away the icon attribute from google.maps.Marker object the default marker shows. So that indicates that it somehow can't find my image... right?
Even when I hardcode the following link
https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png
that marker image shows. But not the one I have locally in my project.
var map = null;
var mapHub;
var markers = [];
$(function ()
{
mapHub = $.connection.myHub;
//Start the hub
$.connection.hub.start(function ()
{
//Get the current location from the browser
navigator.geolocation.getCurrentPosition(function (position)
{
//Create the map element on the page.
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: position.coords.latitude, lng: position.coords.longitude },
zoom: 15
});
//Add marker of current position to map
markers.push(new google.maps.Marker({
position: { lat: position.coords.latitude, lng: position.coords.longitude},
map: map,
icon: '~/Images/MapMarkerIcon.jpg'
}));
});
});
});
I am trying to develop a web application which allows the user to post notes (markers) on the map for others to read. It is basically placing markers on the map that consist of the subject and the message. It is accessed by clicking on a marker on the map.
Right now I am facing an issue with regards of retrieving the data from Firebase. I managed to make the application send data to Firebase (latitude and longitude for marker location on the map, and the message with the subject itself), but I am unable to take the information back in order to place a marker on the exact coordinates.
I followed many YouTube tutorials and online guides but the Firebase data won't show anywhere except for the console in Chrome.
Any clue what could be the issue? I am posting the JavaScript for he map and Firebase below so you can see how I saved message, subject, latitude and longitude to Firebase database.
Thanks
firebase.initializeApp(config);
var note = firebase.database().ref("note");
/*map*/
window.onload = getLocation;
var geo = navigator.geolocation;
function getLocation() {
if (geo) {
geo.watchPosition(displayLocation);
}
else {
alert("opps, geolocation API is not supported ");
}
}
function displayLocation(position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
/*diaplays coordinates in the footer of the webapp*/
var div = document.getElementById( 'location' );
longText = document.getElementById("longitude")
if (latitude == latitude)
{
div.innerHTML = "X: " + latitude + " Y: " + longitude;
}
}
/*map*/
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6,
disableDefaultUI: true,
});
infoWindow = new google.maps.InfoWindow;
/*gets Navigation, sets the map to current position and posts a marker*/
/*Shouldn't post a marker, code will be removed later when we learn how
to post markers to note locations rather than user locations*/
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
})
var marker = new google.maps.Marker
({
position: pos,
map: map
})
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
handleLocationError(false, infoWindow, map.getCenter());
}
}
/*stores Geolocation in local storage to call it later*/
navigator.geolocation.getCurrentPosition(function(p)
{
localStorage.setItem("latitude", p.coords.latitude);
localStorage.setItem("longitude", p.coords.longitude);
}, function(e){console.log(e)})
/*error handler obviously*/
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);
}
/*button firebase function*/
var submitNote = function () {
var subject = $("#messageSubject").val();
var message = $("#messageContent").val();
var lat = localStorage.latitude;
var lon = localStorage.longitude;
note.push({
"subject": subject,
"message": message,
"latitude": lat,
"longitude": lon
});
};
$(window).load(function () {
$("#noteForm").submit(submitNote);
});
To retrieve the latitude and longitude from the database:
firebase.database().ref().child("markers").on('value').then(function(snapshot) {
snapshot.forEach(function(child) {
var childData = child.val();
var latitudes=child.val().latitude;
var longitudes=child.val().longitude;
});
});
Assuming the database is like this:
markers
pushid
subject: subject
message: message
latitude: lat
longitude: lon
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;
Hi as the question says i'm trying to send my laptops current position using geolocation to my website so that it can display its current location on a Google map. My problem is so far I can only get it to display the servers position, and getting some form of script that runs on the laptop to send to the server is where i'm in trouble, just looking to see if anyone has any ideas how to approach this, as its causing me some difficulty thanks
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
var coords = new google.maps.LatLng(latitude, longitude);
var mapOptions = {
zoom: 15,
center: coords,
mapTypeControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(
document.getElementById("mapContainer"),
mapOptions
);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
});
} else {
alert("Geolocation API is not supported in your browser.");
}
Well, since you aren't giving any code that you have a problem with, I might as well just give you a link to the official Google Maps Gelocation API website page: https://developers.google.com/maps/documentation/business/geolocation/.
On the contact page of my site two things can happen:
The user has geolocation enabled, and a map (map-canvas) will display a route from their location to a predefined location dest. This feature works fine.
The user doesn't have geolocation enabled or chooses not to allow it. An alert will show (works fine), and some text will be added to the directions-panel (works fine). The third thing I want to happen in this scenario is a new map be added to map-canvas that is centred on dest, this feature doesn't seem to be working and I can't figure out why.
Code below should give a good representation of the above:
<script type="text/javascript">
var directionsDisplay;
var directionsService = new google.maps.DirectionsService();
var map;
var dest = "Unit 20, Tallaght Business Centre, Whitestown Road, Tallaght Business Park, Ireland";//53.282882, -6.383155
var ourLocation = {lat : 53.282882, lng : -6.383155}//centre attribute of the map must be a LatLng object and not hardcoded as above
function initGeolocation() {
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition( success, failure );
}
}
//create a new map centered on user's location, display route and show directions
function success(position) {
directionsDisplay = new google.maps.DirectionsRenderer();
coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById("directions-panel"));
calcRoute();
}
//calculate the route from user's location to 'dest'
function calcRoute() {
var start = coords;
var end = dest;
var request = {
origin:start,
destination:end,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(result, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(result);
}
});
}
//tell user geoloc isn't enabled and just plot 'ourLocation' on 'map-canvas'
function failure() {
alert("Your browser does not have geolocation enabled so we can't give you directions to our office. Enable geolocation and try again, or consult the map for our address.");
$("#directions-error-message").css({
visibility: 'visible'
});
var destMapOptions = {
zoom:13,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(ourLocation.lat, ourLocation.lng)
}
map = new google.maps.Map(document.getElementById("map-canvas"), destMapOptions);
}
</script>
Anyone have any ideas why this isn't working? All help appreaciated.
EDIT: Working version above
You need to pass the map a LatLng object for it's centre, not an address. You will need to use Googles LocalSearch services to make that work.
var dest = {
lat : 53.282882,
lng : -6.383155
}
var destMapOptions = {
zoom:12,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: new google.maps.LatLng(dest.lat,dest.lng)
}
Also, as you have map declared as a var already maybe use that rather than a function scoped variable for the map.
The center attribute of the map options must be a LatLng object. You've got it hardcoded as an address string.