Locate user position with google maps v3 - javascript

Here I have a code for show a places for users, but I want to show places based on user location.
How I can get user's location and show on map?
I have:
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script>
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds); ... ... ... etc.
I try to add on sensor:true, but it didn't work.
Is there any way to solve this?

You can try to geolocate your user with the browser's built-in geolocation service (which uses the W3C Geolocation standard, so should be supported by all browsers that support HTML5).
There's code you can copy and paste in the Google Maps JavaScript API v3 documentation, here: https://developers.google.com/maps/documentation/javascript/examples/map-geolocation
(The sensor parameter, by the way, just tells Google that you're using a sensor to determine position; it doesn't act as a sensor itself).

Include this to locate the map center at current coordinates:
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: 'Here you are.'
});
map.setCenter(pos);
});
}

Related

How can I change marker position eventually in google maps api?

I have a problem with google maps api, when I change the marker position constantly, this leave a trace on map and I need move the marker without leaving a trace.
I actually get the latitude and the longitude from a database in firebase and need represent the route of a car.
var mapOptions = {
center: new google.maps.LatLng(20.615977, -103.339358),
zoom: 12
};
var map = new google.maps.Map(document.getElementById("map"), mapOptions);
firebase.database().ref('route').on('value', function(data) {
var start = new google.maps.Marker({
position: {lat: latitud, lng: longitud},
map: map,
icon: '../icon/car.png'
});
var myLatlng = new google.maps.LatLng(data.val().latitude, data.val().longitude);
start.setPosition(myLatlng);
start.setMap(map);
});
You're creating a new marker in every event. Instead, create the marker before the event handler (and call setMap there), and in your handler, just do setPosition() to the data's new lat/lng.

Google Maps: Marker will not show up?

"use strict"; // eslint-disable-line
var map;
var initialLocation;
// TODO: Initialize and display Google Map
function initialize() {
//get current location
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
var mapProp = {
center:initialLocation,
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I am trying to set a marker to my current location using Javascript. When I load the map, however, while the map will center on my current location, no marker will appear?
Everything looks good, just add marker.setPosition(initialLocation); in the following section:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(initialLocation);// ****** missing line ******
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
};
Here is a working JSFiddle with the necessary changes.
The key is from a Google MAP API sample and will need to be updated with your own, which you can obtain here: Google MAP API.
You may need to reload the JSFiddle example, as there appears to be an issue with the async defer coming from googleapis file. Wait a few seconds and press RUN.
Just make sure the content of variable initialLocation.
If it has the correct lon/lat, marker will appear.
You have to make sure it has correct value before the following:
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});

google map api, link to URL

Sorry for asking a simple question I surely can find easily by reading the API docs, but a client just asked me this in general, and I would like to answer him asap.
Situation:
I have a custom map created, with public (or restricted to user) access, where are different markers.
Q1)Is it possible to create markers via the API using e.g. custom data from our database?
Q2)Ist it possible to add a URL to a marker, so that a user clicks on it and gets to a specific site, where he can e.g. vote for this location? (just as an example)
Thanks in advance to everyone, and once more sorry not to look closer by myself
Cheers,
Phil
Following Function Will Create Marker
<script type="text/javascript">
// Standard google maps function
function initialize() {
var myLatlng = new google.maps.LatLng(40.779502, -73.967857);
var myOptions = {
zoom: 12,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
TestMarker();
}
// Function for adding a marker to the page.
function addMarker(location) {
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Testing the addMarker function
function TestMarker() {
CentralPark = new google.maps.LatLng(37.7699298, -122.4469157);
addMarker(CentralPark);
}
For Clicking and URL Use Following Technique
var points = [
['name1', 59.9362384705039, 30.19232525792222, 12, 'www.google.com'],
['name2', 59.941412822085645, 30.263564729357767, 11, 'www.amazon.com'],
['name3', 59.939177197629455, 30.273554411974955, 10, 'www.stackoverflow.com']
];
var marker = new google.maps.Marker({
...
zIndex: place[3],
url: place[4]
});
google.maps.event.addListener(marker, 'click', function() {
window.location.href = this.url;
});

Google Map not showing up on my page

i am trying to implement google map in chrome, however the geolocation doesn't seems to be working i also changed the setting to 'allow all site to track'
i have taken these code from a tutorial online, and hence i couldn't find a way to make it work
<head>
<title>Map</title>
<!-- Google Maps and Places API -->
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?libraries=places&sensor=false"></script>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
function initGeolocation(){
if( navigator.geolocation ){
// Call getCurrentPosition with success and failure callbacks
navigator.geolocation.getCurrentPosition( success, fail );
}else{
alert("Sorry, your browser does not support geolocation services.");
}
}
var map;
function success(position){
// Define the coordinates as a Google Maps LatLng Object
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// Prepare the map options
var mapOptions = {
zoom: 14,
center: coords,
mapTypeControl: false,
navigationControlOptions: {style: google.maps.NavigationControlStyle.SMALL},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
// Create the map, and place it in the map_canvas div
map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
//search for schools within 1500 metres of our current location, and as a marker use school.png
//placesRequest('Schools',coords,1500,['school']);
// Place the initial marker
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "Your current location!"
});
}
function fail(){
// Could not obtain location
}
//Request places from Google
function placesRequest(title,latlng,radius,types,icon){
//Parameters for our places request
var request = {
location: latlng,
radius: radius,
types: types
};
//Make the service call to google
var callPlaces = new google.maps.places.PlacesService(map);
callPlaces.search(request, function(results,status){
//trace what Google gives us back
$.each(results, function(i,place){
var placeLoc = place.geometry.location;
var thisplace = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: icon,
title: place.name
});
})
});
}
</script>
initGeolocation() is not fired anywhere.
The div with id map_canvas is missing and you don't call initGeolocation function anywhere in your code .
Check here , everything works ok

Google Maps V3 save map position after user used drag&drop

So I display a map on my website and I want after the user has used his mouse to drag around the map and hits a submit button on the site to save the current map status, in order to display it later on, so what I need is to get the current lat and long of the map after the user has used the map.
So afterwards if the user comes back I can display the same map by setiing LatLng
<script
type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapCanvas, mapOptions);
}
//LE
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&callback=initialize"></script>
<script type="text/javascript">
var map;
function initialize() {
var mapCanvas = document.getElementById('map_canvas');
var mapOptions = {
center: new google.maps.LatLng(44.5403, -78.5463),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(mapCanvas, mapOptions);
}
$(window).load(function(){
google.maps.event.addDomListener(window, 'load', initialize);
});
$(document).ready(function(){
var currentLL = map.getCenter(); // you can even store it in localStorage
var currentZoom = map.getZoom();
console.log(currentLL);
});
</script>
Once the user hits the submit button, get the center position(lat/lng) of the Google Maps. This is the wise option to retain the map.
var currentLL = map.getCenter(); // you can even store it in localStorage
var currentZoom = map.getZoom(); // better to save zoom level too
once you return back to maps, set it has center
map.setCenter(currentLL);
map.setZoom(currentZoom);
You can use #Praveen's solution, but don't place that code in document ready function. Place it in a separate function and call that function when the user hits the save button.
Or you can use the Maps API event listeners for that.
You mentioned that you want to save the location when hitting a button and after the user has used his mouse to drag around the map. I suggest that you get the center and zoom when the map becomes idle. That is, when the map becomes idle after panning or zooming. See the documentation.
You could use the dragend event but that would not work if the user only changed the zoom level.
google.maps.event.addListener(map, 'idle', function() {
currentLL = map.getCenter();
currentZoom = map.getZoom();
console.log(currentLL, currentZoom);
});
This way, you always have the latest center and zoom level available.
JSFiddle demo

Categories

Resources