google maps api center on my location with a button - html

Everything is working but I would really like for the last button (GPS) (sorry can't post image)
to center the map on the user location instead of just refreshing the map like I currently have it set up to do.
An example of how this would work is for the user to have the webpage open and scroll around the map, possibly changing to satellite view, then be able to click the above button (or any button for that matter) and have the map pan back to their location. Not sure if this is even possible, but I can't seem to figure it out on my own. Any help is very much appreciated. Here is the link to my Frankenstein map. http://deepfrogphoto.com/Brett-Pelletier-Photography/Links/maps/wasatch-ski-map-mobile.htm
var map, GeoMarker;
function toggleLayer(this_layer){
if(this_layer.getMap()) {
this_layer.setMap(null)
} else {
this_layer.setMap(map);}}
function initialize() {
var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(40.563855, -111.675426),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
layer1 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "skilines",
from: "1R5pCEyNN74N8Dt9MkfNXA6A9D1HbQESzOR1fYFa7",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer2 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "resorts",
from: "19iu58FDFcBIZZ-wU1iZcf89AI5ABDJ7YTv355su5",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer3 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "summerhiking",
from: "1t1XNnG7J7Zu1p5mIUpm6qIGVYwzhkCgPy_je0IKr",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer4 = new google.maps.KmlLayer('URL-to-KML.kml',
{
suppressInfoWindows: false,
map: map,
preserveViewport: true
});
}
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');}
//]]>
</script>
<title>Wasatch Map by deepfrogphoto</title>
</head>
<body>
<b>Wasatch Map by deepfrogphoto -</b>
<form>
<button onclick="myFunction()">Center Map on My Location</button>
</form>
<div id="map_canvas"></div>
</body>

add a button with onclick event listener
<button onclick="myFunction()">Center</button>
then create the myFunction to center the map to user position
function myFunction(){
Map.panTo(UserCords);//UserCords = user current latitude, longitude. I suppose you have them!!!
}
EDIT
function myFunction(){
if (navigator.geolocation){
navigator.geolocation.getCurrentPosition(getPosition,showError);
}
else{
alert("Geolocation is not supported by this browser.");
}
}
function getPosition(position)
{
UserLatitude = position.coords.latitude;
UserLongitude = position.coords.longitude;
showPosition(UserLatitude, UserLongitude);
}
function showPosition(userLatitude, userLongitude){
lat= userLatitude;
lon= userLongitude;
latlon=new google.maps.LatLng(lat, lon);
YourMap.panTo(latlon);
}
function showError(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED:
alert("User denied the request for Geolocation.");
break;
case error.POSITION_UNAVAILABLE:
alert("Location information is unavailable.")
break;
case error.TIMEOUT:
alert("The request to get user location timed out.")
break;
case error.UNKNOWN_ERROR:
alert("An unknown error occurred.")
break;
}
}

Related

google maps api add button to pan back to user location using geolocationmarker-compiled.js

Here is my code... and i'm using ../geolocationmarker-compiled.js to find the user location.
http://deepfrogphoto.com/Brett-Pelletier-Photography/Links/maps/wasatch-ski-map-mobile.htm
I would love to add a button that pans (centers) back to the user location if they scroll around on the map and want to go back to their location (the nice blue dot) Can anyone help me out? I have no idea what I'm doing, but got all this to work somehow so far. I would be forever grateful to add a button that will pan back to the user location. Thanks for any help ahead of time...
var map, GeoMarker;
function toggleLayer(this_layer){
if(this_layer.getMap()) {
this_layer.setMap(null)
} else {
this_layer.setMap(map);
}
}
function initialize() {
var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(40.563855, -111.675426),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({fillColor: '#808080'});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
layer1 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "skilines",
from: "1R5pCEyNN74N8Dt9MkfNXA6A9D1HbQESzOR1fYFa7",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer2 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "resorts",
from: "19iu58FDFcBIZZ-wU1iZcf89AI5ABDJ7YTv355su5",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer3 = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "summerhiking",
from: "1t1XNnG7J7Zu1p5mIUpm6qIGVYwzhkCgPy_je0IKr",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
if(!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
you can recenter the map on the GeoMarker like this:
map.setCenter(GeoMarker.getPosition());
working code snippet:
var map, GeoMarker;
function toggleLayer(this_layer) {
if (this_layer.getMap()) {
this_layer.setMap(null)
} else {
this_layer.setMap(map);
}
}
function originalCenter() {
map.setCenter(new google.maps.LatLng(40.563855, -111.675426));
}
function recenterMapOnGeoLoc() {
map.setCenter(GeoMarker.getPosition());
}
function initialize() {
var mapOptions = {
zoom: 20,
center: new google.maps.LatLng(40.563855, -111.675426),
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
GeoMarker = new GeolocationMarker();
GeoMarker.setCircleOptions({
fillColor: '#808080'
});
google.maps.event.addListenerOnce(GeoMarker, 'position_changed', function() {
map.setCenter(this.getPosition());
map.fitBounds(this.getBounds());
});
google.maps.event.addListener(GeoMarker, 'geolocation_error', function(e) {
alert('There was an error obtaining your position. Message: ' + e.message);
});
GeoMarker.setMap(map);
trafficLayer = new google.maps.TrafficLayer();
trafficLayer.setMap(map);
layer1 = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "skilines",
from: "1R5pCEyNN74N8Dt9MkfNXA6A9D1HbQESzOR1fYFa7",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer2 = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "resorts",
from: "19iu58FDFcBIZZ-wU1iZcf89AI5ABDJ7YTv355su5",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
layer3 = new google.maps.FusionTablesLayer({
map: map,
heatmap: {
enabled: false
},
query: {
select: "summerhiking",
from: "1t1XNnG7J7Zu1p5mIUpm6qIGVYwzhkCgPy_je0IKr",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
if (!navigator.geolocation) {
alert('Your browser does not support geolocation');
}
html,
body,
#map_canvas {
width: 100%;
height: 100%;
}
<script src="http://maps.google.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
<script src="https://cdn.jsdelivr.net/gh/googlemaps/v3-utility-library#master/archive/geolocationmarker/src/geolocationmarker.js"></script>
<input type="button" id="recenter" onclick="recenterMapOnGeoLoc();" value="recenter" />
<input type="button" id="original" onclick="originalCenter();" value="original center" />
<div id="map_canvas"></div>
working jsfiddle

show google map inside a jquery dialogue form

Hi i'm trying to show a map in my form inside a jquery dialogue,
my jquery dialogue return a partial view where i put this code inside #section scripts and i called also the maps api
<script type="text/javascript">
$(document).ready(function () {
Initialize();
});
// Where all the fun happens
function Initialize() {
// Google has tweaked their interface somewhat - this tells the api to use that new UI
google.maps.visualRefresh = true;
var Liverpool = new google.maps.LatLng(53.408841, -2.981397);
// These are options that set initial zoom level, where the map is centered globally to start, and the type of map to show
var mapOptions = {
zoom: 14,
center: Liverpool,
mapTypeId: google.maps.MapTypeId.G_NORMAL_MAP
};
// This makes the div with id "map_canvas" a google map
var map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions);
// This shows adding a simple pin "marker" - this happens to be the Tate Gallery in Liverpool!
var myLatlng = new google.maps.LatLng(53.40091, -2.994464);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Tate Gallery'
});
// You can make markers different colors... google it up!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/green-dot.png')
// a sample list of JSON encoded data of places to visit in Liverpool, UK
// you can either make up a JSON list server side, or call it from a controller using JSONResult
var data = [
{ "Id": 1, "PlaceName": "Liverpool Museum", "OpeningHours": "9-5, M-F", "GeoLong": "53.410146", "GeoLat": "-2.979919" },
{ "Id": 2, "PlaceName": "Merseyside Maritime Museum ", "OpeningHours": "9-1,2-5, M-F", "GeoLong": "53.401217", "GeoLat": "-2.993052" },
{ "Id": 3, "PlaceName": "Walker Art Gallery", "OpeningHours": "9-7, M-F", "GeoLong": "53.409839", "GeoLat": "-2.979447" },
{ "Id": 4, "PlaceName": "National Conservation Centre", "OpeningHours": "10-6, M-F", "GeoLong": "53.407511", "GeoLat": "-2.984683" }
];
// Using the JQuery "each" selector to iterate through the JSON list and drop marker pins
$.each(data, function (i, item) {
var marker = new google.maps.Marker({
'position': new google.maps.LatLng(item.GeoLong, item.GeoLat),
'map': map,
'title': item.PlaceName
});
// Make the marker-pin blue!
marker.setIcon('http://maps.google.com/mapfiles/ms/icons/blue-dot.png')
// put in some information about each json object - in this case, the opening hours.
var infowindow = new google.maps.InfoWindow({
content: "<div class='infoDiv'><h2>" + item.PlaceName + "</h2>" + "<div><h4>Opening hours: " + item.OpeningHours + "</h4></div></div>"
});
// finally hook up an "OnClick" listener to the map so it pops up out info-window when the marker-pin is clicked!
google.maps.event.addListener(marker, 'click', function () {
infowindow.open(map, marker);
});
})
}
i'm calling the map inside a div :
<div id="map_canvas" style="height: 240px; border: 1px solid gray"> map here</div>
but the problem that my map is not showing in the dialogue, even though it works well in normal page
any help plz !?
I've solved this issue with the following code:
this code is on the main view, the #next is a trigger of the form to submit, and the #dialog is inside the #form.
$(function () {
datepair();
$('#dialog').dialog({
autoOpen: false,
modal: true,
height: 720,
width: 700,
resizable: false,
title: 'Verify Location',
show: "fade",
hide: "fade",
open: function (event, ui) {
var form = $('#form');
$.ajax({
url: form.attr('actoin'),
type: form.attr('method'),
data: form.serialize(),
context: this,
success: function (result) {
$(this).html(result);
}
});
}
});
$('#next').click(function (e) {
$('#dialog').dialog('open');
return false;
});
});
this code is on the partialView
$(function () {
window.$required = $('<div></div>').dialog({
autoOpen: false,
resizable: false,
modal: true,
title: 'Verity Location Error',
buttons: {
"Ok": function () {
$(this).dialog('close');
callback();
}
}
});
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function (json) {
Initialize();
}
});
return false;
});
function callback() {
$('#dialog').dialog('close');
}
function Initialize() {
//init the map
}
and this is the controller
public ActionResult PartialViewMapController()
{
return PartialView();
}
Hope it not to late for you :)

Google Place API v3 with Sencha Touch 2.x

I am new to Sencha Touch, knows Javascript,jQuery,HTML5.
I am developing simple Google Map application with Sencha Touch + Sencha Architect where it place marker on current position and also use Google Place to find 'store'(i.e. types need for Google place search) near the current location. I am getting the locations in 'callbackPlaces' (i.e. latitude, longitude) but Google.Maps.Marker gives error in 'callbackPlaces' method (i.e. called through 'addMarker' method and I also tried and tested by putting Google.Maps.Marker in 'callbackPlaces').
Ext.define('MyApp.view.Map', {
extend: 'Ext.Map',
alias: 'widget.map',
config: {
useCurrentLocation: true,
listeners: [
{
fn: 'onMapMaprender',
event: 'maprender'
}
]
},
onMapMaprender: function(map, gmap, options) {
this.initializePlaces();
},
initializePlaces: function() {
//Set Marker on Current Position
var geo = this.getGeo();
var currentPosition = new google.maps.LatLng(geo.getLatitude(), geo.getLongitude());
this.createMarker(currentPosition);
//request set for Places Services
var request = {
location: currentPosition,
radius: 500,
types: ['store']
};
this.getMap().zoom = 15;
// Call PlacesService
var service = new google.maps.places.PlacesService(this.getMap());
service.nearbySearch(request, this.callbackPlaces);
},
callbackPlaces: function(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
addMarker(results[i]);
}
}
},
createMarker: function(position) {
//Here Position = Google Map LatLng
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: position
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
},
addMarker: function() {
//Here Place = google.maps.places
var infoWindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: this.getMap(),
position: place.geometry.location
});
google.maps.event.addListener(marker, "click", function() {
infoWindow.setContent("Lng: " + marker.position.lng() + "\n Lat: " + marker.position.lat());
infoWindow.open(this.getMap(), marker);
});
}
});
I don't know what went wrong!
Any help|hint would appreciated!
Thanks in advance.
You pointed out there was a scope issue in the callbackPlaces function.
Therefore you should replace the following line:
service.nearbySearch(request, this.callbackPlaces);
with
service.nearbySearch(request, function (results, status) {
this.callbackPlaces.call(this, [results, status]);
});
Hope this helps

jQuery Google Maps Adding a Marker on Click

i am using gmaps.js (https://github.com/hpneo/gmaps)
I want to add a Marker on the map on clicking a location on the map. If a user clicks on a second location the previous marker should move to the new place or be removed and replaced with a new marker.
Now sure if this is supported by the Lib.
http://bakasura.in/startupsradar/add.html
$(document).ready(function () {
var map = new GMaps({
div: '#map',
lat: 13.00487,
lng: 77.576729,
zoom: 13
});
map.addMarker({
lat: 13.00487,
lng: 77.576729,
title: 'Mink7',
infoWindow: {
content: 'HTML Content'
}
});
/*
GMaps.geolocate({
success: function (position) {
map.setCenter(position.coords.latitude, position.coords.longitude);
},
error: function (error) {
alert('Geolocation failed: ' + error.message);
},
not_supported: function () {
alert("Your browser does not support geolocation");
},
always: function () {
//alert("Done!");
}
});
*/
});
google.maps.event.addListener(_map, "click", function(event) {
if(_marker) {
_marker.setPosition(event.latLng);
} else {
_marker = new google.maps.Marker({
position: event.latLng,
map: _map,
title: "myTitle"
});
}
});
Just saw the other answer, use this if you dont want to create a marker everytime..
_marker should be a global variable.
Personally, I do it using a global variable for the marker (or an array if I need more markers and I want to access them later), so that I can delete it and recreate it somewhere else.
// instantiate your var map
// ...
google.maps.event.addListener(map, "click", function(event) {
if(markermap) {
markermap.setMap(null);
}
markermap = new google.maps.Marker({
position: event.latLng,
map: myMap,
title: "myTitle"
});
});

init gmap3 using geocode

I am new to gmap3, is it possible to init the gmap3 using a place address?
I know generally it is done with latitude and longitude.
I have done markers with this this location name using this example.
I have already gone through this example too, but no luck.
And also i need to zoom the places on selection, i use auto complete for this purpose.
My code is given below
$('#test').gmap3(
{ action:'init',
options:{
address: "kerala,india"
}
}
);
First use getLatLng() to retrieve the location, when successfull set the center:
$('#test1').gmap3(
{ action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({action: 'setCenter', args:[ result[0].geometry.location ]},
{action: 'setZoom', args:[ 12]});
} else {
alert('not found !');
}}});
var add="kerala,india";
var geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: add, region: 'no' },
function (results, status) {
if (status.toLowerCase() == 'ok') {
// Get center
var coords = new google.maps.LatLng(
results[0]['geometry']['location'].lat(),
results[0]['geometry']['location'].lng()
);
//alert(coords);
$map.gmap3("get").setCenter(coords);
$map.gmap3("get").setZoom(12);
addMarker(coords);
}
else {
alert("address not found");
}
}
function addMarker(marker) {
$map = $('#googleMap');
if (marker) {
$map.gmap3(
{ action: 'init',
options: {
center: eval(marker),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
},
{ action: 'addMarker',
latLng: eval(marker),
options: {
draggable: true,
icon: new google.maps.MarkerImage('http://maps.google.com/mapfiles/marker.png')
},
events: {
dragend: function (mark) {
updateMarker(mark);
}
}
});
}
}
Using above code you can get latitude/longitude also and drag searched location marker.
This feature will be in next version (5.0), current is not updated,
here is a working code :
$('#test1').gmap3({
action : 'getLatLng',
address:'kerala,india',
callback : function(result){
if (result){
$(this).gmap3({
action: "init",
options:{
center: result[0].geometry.location,
zoom: 12
}
});
} else {
alert('not found !');
}
}
});
notice, if your map is already initialized, you can use in the callback
$(this).gmap3("get").setCenter(result[0].geometry.location);
$(this).gmap3("get").setZoom(12);
You can use the following code as well:
var markerData = [];
markerData.push({ address: 'kerala,india', data: '' });
$('#test').gmap3({
action: 'addMarkers',
markers: markerData
}
);