Show My Location on Google Maps API v3 - html

"My Location" in Google Maps javascript API
This question was asked over half a year ago. Has Google Maps API v3 updated to use the "My Location" button found on http://maps.google.com?
My Location is the control between the Street View man and the gamepad-looking controls.
If Google Maps API doesn't provide My Location then do I need to write my own HTML5 geolocation feature using navigator.gelocation then create my own control on Google Maps?

No, but adding your own marker based on current location is easy:
var myloc = new google.maps.Marker({
clickable: false,
icon: new google.maps.MarkerImage('//maps.gstatic.com/mapfiles/mobile/mobileimgs2.png',
new google.maps.Size(22,22),
new google.maps.Point(0,18),
new google.maps.Point(11,11)),
shadow: null,
zIndex: 999,
map: // your google.maps.Map object
});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(pos) {
var me = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
myloc.setPosition(me);
}, function(error) {
// ...
});
}

We have made such a component for Google Maps API v3. Anybody can use in custom projects to add a control showing current geolocation with just one line of code:
var geoloccontrol = new klokantech.GeolocationControl(map, mapMaxZoom);
after including in the HTML header this JavaScript:
<script src="https://cdn.klokantech.com/maptilerlayer/v1/index.js"></script>
See:
http://www.maptiler.com/maptilerlayer/
for an example code and documentation.
It adds the standard control to the map - and once tapped - it shows the blue circle around your location with size derived from precision of the location data available. If you don't drag the map it will keep you positioned once you move.
This control has been developed for viewer automatically generated by http://www.maptiler.com/ software - which creates tiles for map overlays and custom layers made from images and raster geodata.

you have to do it by your own. Here is a piece of code to add "Your Location" button.
HTML
<div id="map">Map will be here</div>
CSS
#map {width:100%;height: 400px;}
JS
var map;
var faisalabad = {lat:31.4181, lng:73.0776};
function addYourLocationButton(map, marker)
{
var controlDiv = document.createElement('div');
var firstChild = document.createElement('button');
firstChild.style.backgroundColor = '#fff';
firstChild.style.border = 'none';
firstChild.style.outline = 'none';
firstChild.style.width = '28px';
firstChild.style.height = '28px';
firstChild.style.borderRadius = '2px';
firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
firstChild.style.cursor = 'pointer';
firstChild.style.marginRight = '10px';
firstChild.style.padding = '0px';
firstChild.title = 'Your Location';
controlDiv.appendChild(firstChild);
var secondChild = document.createElement('div');
secondChild.style.margin = '5px';
secondChild.style.width = '18px';
secondChild.style.height = '18px';
secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
secondChild.style.backgroundSize = '180px 18px';
secondChild.style.backgroundPosition = '0px 0px';
secondChild.style.backgroundRepeat = 'no-repeat';
secondChild.id = 'you_location_img';
firstChild.appendChild(secondChild);
google.maps.event.addListener(map, 'dragend', function() {
$('#you_location_img').css('background-position', '0px 0px');
});
firstChild.addEventListener('click', function() {
var imgX = '0';
var animationInterval = setInterval(function(){
if(imgX == '-18') imgX = '0';
else imgX = '-18';
$('#you_location_img').css('background-position', imgX+'px 0px');
}, 500);
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(latlng);
map.setCenter(latlng);
clearInterval(animationInterval);
$('#you_location_img').css('background-position', '-144px 0px');
});
}
else{
clearInterval(animationInterval);
$('#you_location_img').css('background-position', '0px 0px');
}
});
controlDiv.index = 1;
map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
}
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 15,
center: faisalabad
});
var myMarker = new google.maps.Marker({
map: map,
animation: google.maps.Animation.DROP,
position: faisalabad
});
addYourLocationButton(map, myMarker);
}
$(document).ready(function(e) {
initMap();
});

//copy and paste this in your script section.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success, error);
} else {
alert('location not supported');
}
//callbacks
function error(msg) {
alert('error in geolocation');
}
function success(position) {
var lats = position.coords.latitude;
var lngs = position.coords.longitude;
alert(lats);
alert(lngs)
};

Related

Algolia and google filter results based on user position

Hi I am using Google maps alongside algolia where I have an index 'locations' with 'lat' and 'lng'.
I am getting user location and watching position, I am also displaying markers from database based on lng and lat however I want to add a bit to it:
So I have followed that link:
https://www.algolia.com/doc/guides/geo-search/geo-search-overview/
And came up with:
#extends('master') #section('title', 'Live Oldham')
#section('extrafiles')
<script type="text/javascript" src="https://maps.google.com/maps/api/js?v=3&key=AIzaSyAirYgs4Xnt9QabG9v56jsIcCNfNZazq50&language=en"></script>
<script type="text/javascript" src="{!! asset('js/homesearch.js') !!}"></script>
#endsection
#section('content')
<div id="map_canvas" style="height:600px;"></div>
#endsection
and js:
$(document).ready(function() {
var map;
function initializeMap(){
map = new google.maps.Map(document.getElementById('map_canvas'), {
zoom: 19,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function locError(error) {
// the current position could not be located
alert("The current position could not be found!");
}
function setCurrentPosition(position) {
currentPositionMarker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
),
title: "Current Position"
});
map.panTo(new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude
));
}
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
console.log(latitude);
console.log(longitude);
function displayAndWatch(position) {
// set current position
setCurrentPosition(position);
// watch position
watchCurrentPosition(position);
console.log(position);
}
function watchCurrentPosition(position) {
var positionTimer = navigator.geolocation.watchPosition(
function (position) {
setMarkerPosition(
currentPositionMarker,
position,
)
});
}
function setMarkerPosition(marker, position) {
marker.setPosition(
new google.maps.LatLng(
position.coords.latitude,
position.coords.longitude)
);
}
function initLocationProcedure() {
initializeMap();
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(displayAndWatch, locError);
}else{
alert("Your browser does not support the Geolocation API");
}
}
$(document).ready(function() {
initLocationProcedure();
});
var APPLICATION_ID = '75RQSC1OHE';
var SEARCH_ONLY_API_KEY = 'f2f1e9bba4d7390fc61523a04685cf12';
var INDEX_NAME = 'locations';
var PARAMS = { hitsPerPage: 100 };
// Client + Helper initialization
var algolia = algoliasearch(APPLICATION_ID, SEARCH_ONLY_API_KEY);
var algoliaHelper = algoliasearchHelper(algolia, INDEX_NAME, PARAMS);
// Map initialization
var markers = [];
//alert("heelo");
var fitMapToMarkersAutomatically = true;
algoliaHelper.on('result', function(content) {
renderHits(content);
var i;
// Add the markers to the map
for (i = 0; i < content.hits.length; ++i) {
var hit = content.hits[i];
console.log(hit)
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
markers.push(marker);
}
// Automatically fit the map zoom and position to see the markers
if (fitMapToMarkersAutomatically) {
var mapBounds = new google.maps.LatLngBounds();
for (i = 0; i < markers.length; i++) {
mapBounds.extend(markers[i].getPosition());
}
map.fitBounds(mapBounds);
}
});
function renderHits(content) {
$('#container').html(JSON.stringify(content, null, 2));
}
algoliaHelper.setQueryParameter('aroundRadius', 5000).search(); // 5km Radius
});
However there are few problems with this that I don't know how to tackle:
When user is moving, it doesn't center the map on the marker.
At this moment marker jumps between location when user moves, I would like for the marker to dynamically move on the map when user moves.
I want to use algolia to dynamically set markers, so I want to show markers with 5km radius from user location, and dynamically add or remove markers that are outside it.
I can't help you much with those questions since it's mostly about how to use GMap JS lib and I'm not experienced with it. However, something else catched my eyes:
var marker = new google.maps.Marker({
position: {lat: hit.longitude, lng: hit.latitude},
map: map,
title: hit.slug
});
You should put your coordinates in the _geoloc field in order to be able to use the geo-search features. It looks like this:
_geoloc: {
lat: 40.639751,
lng: -73.778925
}

retrieving latitude and longitude from database(db2) and show in map in IBM worklight

I have saved latitude and longitude in database(db2).I want to use them to show their location in map.I am working with IBM Worklight and as database I am using DB2.
My problem is I can retrieve value from database,store it in a variable but could not be able to pass the value in the function of map where it can be used as latitude and longitude.
Any positive help would be appreciated.Thanks in advance.
My approach:
CODE:
var mylat;
var mylon;
var clat;
var clon;
function maplo() {
//database value,I have stored them in a text input type
clat=$("#lati").val();
clon=$("#long").val();
}
var x = document.getElementById("demo");
function getLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition);
} else {
x.innerHTML = "Geolocation is not supported by this browser.";
}
}
function showPosition(position) {
x.innerHTML = "Latitude: " + position.coords.latitude +
"<br>Longitude: " + position.coords.longitude;
mylat=position.coords.latitude;
mylon=position.coords.longitude;
}
function success(position) {
//reload();
maplo();
showPosition(position);
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('article').appendChild(mapcanvas);
var flat=clat;
var flon=clon;
alert("custom latitude is : "+flat);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var coords1 = new google.maps.LatLng(flat, flon);
var options = {
zoom: 16,
center: coords,
mapTypeControl: false,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.SMALL
},
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position: coords,
map: map,
title:"You are here!"
});
var geolocation = new google.maps.Marker({
position: coords1,
map: map,
title: 'Your car location',
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(success);
} else {
error('Geo Location is not supported');
}
function searchcarl()
{
var a=$("#searchcar").val();
var invocationData={
adapter:'park',
procedure :'procedure4',
parameters:[a]
};
var options={
onSuccess:success6,
onFailure:fail6
};
WL.Client.invokeProcedure(invocationData, options);
}
function success6(result){
if((result.invocationResult.resultSet.length)>0)
{
alert("location fetching!");
var I=result.invocationResult.resultSet[0].LAT;
var J=result.invocationResult.resultSet[0].LON;
$("#lati").val(I);
$("#long").val(J);
}
else{
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function fail6()
{
alert("fail6");
}
I will update the code as follows:
// create a map global variable
var map;
function initMap(position) {
var mapcanvas = document.createElement('div');
mapcanvas.id = 'mapcontainer';
mapcanvas.style.height = '460px';
mapcanvas.style.width = '320px';
document.querySelector('body').appendChild(mapcanvas);
var coords = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var options = {
zoom : 16,
center : coords,
mapTypeControl : false,
navigationControlOptions : {
style : google.maps.NavigationControlStyle.SMALL
},
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("mapcontainer"), options);
var marker = new google.maps.Marker({
position : coords,
map : map,
title : "You are here!"
});
}
// adds a marker to the map
function addCarLocationMarker(lat, lng) {
var coords = new google.maps.LatLng(lat, lng);
var geolocation = new google.maps.Marker({
position : cords,
map : map,
title : 'Your car location',
icon : 'http://labs.google.com/ridefinder/images/mm_20_green.png'
});
}
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
// once you know the user location, init the map
initMap(position);
});
} else {
alert('Geo Location is not supported');
}
function searchcarl() {
var a = $("#searchcar").val();
var invocationData = {
adapter : 'park',
procedure : 'procedure4',
parameters : [ a ]
};
var options = {
onSuccess : adapterSuccess,
onFailure : adapterFailed
};
WL.Client.invokeProcedure(invocationData, options);
}
function adapterSuccess(result) {
if ((result.invocationResult.resultSet.length) > 0) {
alert("location fetching!");
var I = result.invocationResult.resultSet[0].LAT;
var J = result.invocationResult.resultSet[0].LON;
// add the marker directly to the map
addCarLocationMarker(I, J);
}
else {
alert("Incorrect Username or Password!");
window.location.assign("#log");
}
}
function adapterFailed() {
alert("adapter invocation failed");
}
Like Idan mentioned, it's not a good idea to store the coordinates in text boxes to then use the text boxes as the source of the coordinates.
You should add the marker directly after you received the coordinates from the adapter. In this case I created a separate function initMap to initialize the map and center it on the current user's location. It is a good idea to make your functions smaller to perform one single task.
I removed some function that I thought you didn't need or were duplicating functionality namely maplo, getLocation and showPosition.

Centering google map based on user's geolocation

I have a google map (v2) on my website which i use to get user's latitude and longitude to send them as a form. What i need is to make this map initially be centered based on user's geolocation. I understand it's not a practical question but i'm not very familiar with google maps api and all the tutorial's on web are based on google map v3 and i don't want the hassle to migrate to v3 and write all the stuff all over again. So i appreciate it if someone lead me in the right direction to get this feature working on gmap(v2). Here's how my code looks like:
if (GBrowserIsCompatible()) {
var map = new GMap2(document.getElementById("map"));
map.addControl(new GSmallMapControl());
map.addControl(new GMapTypeControl());
var center = new GLatLng(43.65323, -79.38318);
map.setCenter(center, 15);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(initialLocation);
});
}
geocoder = new GClientGeocoder();
var marker = new GMarker(center, {
draggable: true
});
map.addOverlay(marker);
document.getElementById("b-lat").value = center.lat().toFixed(5);
document.getElementById("b-longt").value = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function () {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("b-lat").value = point.lat().toFixed(5);
document.getElementById("b-longt").value = point.lng().toFixed(5);
});
GEvent.addListener(map, "moveend", function () {
map.clearOverlays();
var center = map.getCenter();
var marker = new GMarker(center, {
draggable: true
});
map.addOverlay(marker);
document.getElementById("b-lat").value = center.lat().toFixed(5);
document.getElementById("b-longt").value = center.lng().toFixed(5);
GEvent.addListener(marker, "dragend", function () {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("b-lat").value = point.lat().toFixed(5);
document.getElementById("b-longt").value = point.lng().toFixed(5);
});
});
}
See my other post: Android maps v2 - get map zoom
To simply zoom in, use:
float zoomLevel = 20.0f;
map.animateCamera(CameraUpdateFactory.zoomTo(zoomLevel);
To zoom to the marker, use:
LatLng l = new LatLng(LATPOSITION, LONGPOSITION); float zoomLevel =
20.0f; map.animateCamera(CameraUpdateFactory.newLatLngZoom(l, zoomLevel));
Add these where you want the zoom to happen.
Note: This is for Java android, you may need to edit it for the web.
I found the solution through navigator object. after initializing the map i found the user's lat&longt with this block of code:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
userLatitude = position.coords.latitude;
userLongitude = position.coords.longitude;
center = new GLatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(center, 15);
addMapMarker();
});
if(typeof userLatitude == 'undefined' && typeof userLongitude == 'undefined') {
center = new GLatLng(43.65323, -79.38318);
map.setCenter(center, 15);
addMapMarker();
}
} else {
center = new GLatLng(43.65323, -79.38318);
map.setCenter(center, 15);
addMapMarker();
}

Google maps marker, with added directions code not showing

I seem to be having trouble adding a marker to one of my maps that I have created and I just can't seem to figure out where I am going wrong with it.
The map has been added to the site fine, and I even have the directions code working which happens to be displaying markers.
What I would like would be an initial marker to display where, in this case, the school is and have an info box on click to show the address but I just can't seem to get it displaying no matter what I try.
My code for everything is as follows:-
<div id="map_canvas" style="width:100%; height:392px;float:left;"></div>
<div id="directionsPanel" style="float:left;max-width:395px; overflow:scroll;overflow-x: hidden;"></div>
<script>
//define one global Object
var myMap = {}
//init
function initialize(){
//set up map options
var mapOptions = {
center: new google.maps.LatLng(53.964304,-2.028522),
zoom: 15,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
myMap.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
myMap.directionsService = new google.maps.DirectionsService();
myMap.directionsDisplay = new google.maps.DirectionsRenderer();
myMap.directionsDisplay.setMap(myMap.map);
myMap.directionsDisplay.setPanel(document.getElementById("directionsPanel"));
}//end init
function createMarker(point, title, content, map) {
var marker = new google.maps.Marker({
position: point,
map: map,
title: title
});
var infowindow = new google.maps.InfoWindow({
content: content
});
google.maps.event.addListener(marker, 'click', function() {
if(curr_infw) { curr_infw.close();} // We check to see if there is an info window stored in curr_infw, if there is, we use .close() to hide the window
curr_infw = infowindow; // Now we put our new info window in to the curr_infw variable
infowindow.open(map, marker); // Now we open the window
});
return marker;
}
//directions
var calcRoute = function() {
var start = document.getElementById("start").value,
end = document.getElementById("end").value,
request = {
origin:start,
destination:end,
durationInTraffic :true,
transitOptions: {
departureTime: new Date()
},
provideRouteAlternatives : true,
travelMode: document.getElementById("travelmode").value
};
myMap.directionsService.route(request, function(result, status) {
if(status == google.maps.DirectionsStatus.OK) {
myMap.directionsDisplay.setDirections(result);
}else{
alert("something went wrong!");
}
});
}
//script loader
var loadScript = function() {
var script = document.createElement("script");
script.type = "text/javascript";
script.src = "http://maps.googleapis.com/maps/api/js?key=AIzaSyDZsY0Xbo137bDtb8wmefTogdGl82QM85s&sensor=false&callback=initialize";
document.body.appendChild(script);
}
window.onload = loadScript;
Any help on this guys would be greatly appreciated before I end up becoming bald from pulling out all my hair lol.
Jason

Display Number on Marker for Google Maps

All,
I've got the following code to display my markers on my maps:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function'){
window.onload = func
} else {
window.onload = function() {
oldonload();
func();
}
}
}
var map,
infowin=new google.maps.InfoWindow({content:'moin'});
function loadMap()
{
map = new google.maps.Map(
document.getElementById('map'),
{
zoom: 12,
mapTypeId:google.maps.MapTypeId.ROADMAP,
center:new google.maps.LatLng(<?php echo $_SESSION['pav_event_latitude']; ?>,
<?php echo $_SESSION['pav_event_longitude']; ?>)
});
addPoints(myStores);
}
function addPoints( points )
{
var bounds=new google.maps.LatLngBounds();
for ( var p = 0; p < points.length; ++p )
{
var pointData = points[p];
if ( pointData == null ) {map.fitBounds(bounds);return; }
var point = new google.maps.LatLng( pointData.latitude, pointData.longitude );
bounds.union(new google.maps.LatLngBounds(point));
createMarker( point, pointData.html );
}
map.fitBounds(bounds);
}
function createMarker(point, popuphtml)
{
var popuphtml = "<div id=\"popup\">" + popuphtml + "<\/div>";
var marker = new google.maps.Marker(
{
position:point,
map:map
}
);
google.maps.event.addListener(marker, 'click', function() {
infowin.setContent(popuphtml)
infowin.open(map,marker);
});
}
function Store( lat, long, text )
{
this.latitude = lat;
this.longitude = long;
this.html = text;
}
var myStores = [<?php echo $jsData;?>, null];
addLoadEvent(loadMap);
</script>
This works great. However I'm trying to say add a number over the marker so that people can relate the number on my site with the marker in Google Maps. How can I go about creating the number over top of my markers (on top of the actual icon and not in an information bubble)?
Any help would be greatly appreciate! Thanks in advance!
EDIT: This API is now deprecated, and I can no longer recommend this answer.
You could use Google's Charts API to generate a pin image.
See: http://code.google.com/apis/chart/infographics/docs/dynamic_icons.html#pins
It'll make and return an image of a marker from the parameters you specify. An example usage would be: https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=2|FF776B|000000
To implement it into your Google Map, it can be added into the new Marker() code:
var number = 2; // or whatever you want to do here
var marker = new google.maps.Marker(
{
position:point,
map:map,
icon:'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld='+number+'|FF776B|000000',
shadow:'https://chart.googleapis.com/chart?chst=d_map_pin_shadow'
}
);
EDIT:
For quite some time now, map markers have an option called label available.
var marker = new google.maps.Marker({
position:point,
map:map,
label: "Your text here."
});
Labels themselves have few options to play with. You can read more about it here.
Original answer
Here is a service similar to one described by Rick - but still active and you can upload your own marker image.
Service is no longer available.