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

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

Related

Center Map to Bounds not working

I am trying to center map to fit all markers. There are lots of example of this, and seems reasonably easy, but I just can't get it to work. Can anyone see what I am doing wrong?
The map can be tested here: http://www.lymphoedema.org.au/the-register/find-a-practitioner-test/ [[Search within 40kms of 3000; then click Map to view the map]].
The map is zoomed right out, and the markers are up in the very top left corner of the map.
Can anyone see what I am doing wrong?
Thank you!
<script type='text/javascript'>
var markers = [];
var marker;
console.log('About to setup map');
//setup the map
function initialize() {
var mapProp = {
draggable: true,
scrollwheel: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("resultmap-canvas"), mapProp);
// show markers
var myLatLng = {lat: -37.8757303, lng: 145.1277893};
var marker6610 = new google.maps.Marker({
position: myLatLng,
map: map
});
marker6610.setValues( {profileid: 6610, directoryid: 2} );
markers.push(marker6610);
var myLatLng = {lat: -38.0034790, lng: 145.1198805};
var marker5316 = new google.maps.Marker({
position: myLatLng,
map: map
});
marker5316.setValues( {profileid: 5316, directoryid: 2} );
markers.push(marker5316);
//set map bounds
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
map.fitBounds(bounds);
}
//execute the map creation
initialize();
// trigger map resize event when map tab is displayed
$("#mapTab").on('shown.bs.tab', function() {
google.maps.event.trigger(map, 'resize');
});
</script>
Your code works fine when tested out of a bootstrap tab. So I guess the resize trigger has some implication in the issue.
Try this way:
Declare your bounds variable outside of the initialize function scope (that is where you define your marker and markers variables). By the way, you are missing the map variable declaration too.
var markers = [];
var marker;
var bounds = new google.maps.LatLngBounds();
var map; // missing in your original code
Then fit the bounds too in the bootstrap shown event:
// trigger map resize event when map tab is displayed
$("#mapTab").on('shown.bs.tab', function() {
google.maps.event.trigger(map, 'resize');
map.fitBounds(bounds); // add this line to your code
});
Don't forget to also remove the var declaration here:
//set map bounds
var bounds = new google.maps.LatLngBounds();
Should now be:
//set map bounds
bounds = new google.maps.LatLngBounds();
This is untested but that's all I can think of right now. Let me know if it works or not.

Google Maps not centering after dynamically loading latitude/longitude on click

I'm dynamically loading latitude/longitude variables and passing them to the Google Maps Initialize(); function.
function initialize() {
var lat = $('.map_img', '.inview').attr('data-lat');
var lng = $('.map_img', '.inview').attr('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.trigger(map, 'resize');
}
So I'm pulling these coordinates via the data attribute, which is set via a wordpress widget and giving them to Google Maps.
I want to run the function, getting new coordinates every time the user clicks these left/right buttons.
previous
next
$('.btn-prev').click(function () {
//initialize maps script again
initialize();
});
$('.btn-next').click(function () {
//initialize maps script again
initialize();
});
Then the user clicks on a Map image which opens the large map with the new coordinates.
var mapImg = $('.map_img');
var $overlay = $('.overlay'),
resize = true,
map;
mapImg.click(function () {
$overlay.show();
if (resize) {
initialize();
resize = false;
}
});
The problem I'm having is that after the first click the Map is not centered. I had assumed google.maps.event.trigger(map, 'resize'); would solve this problem.
I'm not sure why this is happening so I've created a fiddle to replicate the issue.
http://jsfiddle.net/SEOplay/3CXSs/13/
Help much appreciated.
Try using:
google.maps.event.addDomListener(window, "click", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Not efficient code because I'm not excatly sure how it fits into your code, but it will recenter the map every time someone clicks somewhere. It should give you some idea of the code you need, if you have any trouble let me know.
JSFiddle (you also seem to have a bug where it doesn't change the map on the first next/prev click.

Google maps save marker location?

So I managed to implement the google map with a dragable marker on my website.
The only problem I have now is that I don't know how to save the location of where the marker is put the last time. So if a user drags the marker 4 times, I want to save the location (latitude and longitude) of the 4th time only.
This is what I have so far (This is the working code without the code to save the location):
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var map = new GMap2(document.getElementById("googleMap"));
map.addControl(new GLargeMapControl());
map.addControl(new GMapTypeControl());
var centrePoint = new GLatLng('53.34870686020199', '-6.267356872558594');
map.setCenter(centrePoint, 14);
var marker = new GMarker(centrePoint, {draggable: true});
map.addOverlay(marker);
GEvent.addListener(marker, "dragend", function() {
var point = marker.getPoint();
map.panTo(point);
document.getElementById("latitude").value = point.lat();
document.getElementById("longitude").value = point.lng();
});
function initialize ()
{
Brussels = new google.maps.LatLng (50.833333, 4.333333);
myOptions =
{
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP,
center: Brussels,
streetViewControl: false
}
map = new google.maps.Map (document.getElementById ("googleMap"), myOptions);
marker = new google.maps.Marker ({position: Brussels, title: "Brussel, BE"});
marker.setMap (map);
marker.setDraggable (true);
google.maps.event.addListener (marker, 'dragend', function (event)
{
var point = marker.getPosition();
map.panTo(point);
});
}
By save do you mean persist to local storage?
You could modify the dragend event listener so that it updates the local storage with the latitude and longitude of the position the marker was dragged to. As this event is triggered whenever the marker is dragged, the local storage will always contain the location of the last drag (i.e. if the user drags the marker 4 times, local storage will hold the position of the fourth drag).
google.maps.event.addListener (marker, 'dragend', function (event)
{
var point = marker.getPosition();
map.panTo(point);
// save location to local storage
localStorage['lastLat'] = point.lat();
localStorage['lastLng'] = point.lng();
});
Obviously this would only work in browsers that have support for local storage so it would be wise to check for this before attempting to access the local storage

Locate user position with google maps v3

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);
});
}

How to set google map marker by latitude and longitude and provide information bubble

The following sample code provided by google maps api
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
the following only shows google map of the location without a marker.
I was wondering how I can place a marker by giving latitude/longitude parameters?
And how is it possible to store my own information pulled from a database on that marker?
Here is a JSFiddle Demo that shows you how to set a google map marker by Lat Lng and also when click would give you an information window (bubble):
Here is our basic HTML with 3 hyperlinks when clicked adds a marker onto the map:
<div id="map_canvas"></div>
<a href='javascript:addMarker("usa")'>Click to Add U.S.A</a><br/>
<a href='javascript:addMarker("brasil")'>Click to Add Brasil</a><br/>
<a href='javascript:addMarker("argentina")'>Click to Add Argentina</a><br/>
First we set 2 global variables. one for map and another an array to hold our markers:
var map;
var markers = [];
This is our initialize to create a google map:
function initialize() {
var latlng = new google.maps.LatLng(40.77627, -73.910965);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
We then create 3 lat lng locations where we would like to place our markers:
var usa = new google.maps.LatLng(37.09024, -95.712891);
var brasil = new google.maps.LatLng(-14.235004, -51.92528);
var argentina = new google.maps.LatLng(-38.416097, -63.616672);
Here we create a function to add our markers based on whatever is passed onto it. myloc will be either usa, brasil or argentina and we then create the marker based on the passed param. With in the addMarker function we check and make sure we don't create duplicate marker on the map by calling the for loop and if we the passed param has already been created then we return out of the function and do nothing, else we create the marker and push it onto the global markers array. After the marker is created we then attach an info window with it's associated marker by doing markers[markers.length-1]['infowin'] markers.length-1 is just basically getting the newly pushed marker on the array. Within the info window we set the content using html. This is basically the information you put into the bubble or info window (it can be weather information which you can populate using a weather API and etc). After info window is attached we then attach an onclick event listener using the Google Map API's addListener and when the marker is clicked we want to open the info window that is associated with it by calling this['infowin'].open(map, this) where the map is our global map and this is the marker we are currently associating the onclick event with.
function addMarker(myloc) {
var current;
if (myloc == 'usa') current = usa;
else if (myloc == 'brasil') current = brasil;
else if (myloc == 'argentina') current = argentina;
for (var i = 0; i < markers.length; i++)
if (current.lat() === markers[i].position.lat() && current.lng() === markers[i].position.lng()) return;
markers.push(new google.maps.Marker({
map: map,
position: current,
title: myloc
}));
markers[markers.length - 1]['infowin'] = new google.maps.InfoWindow({
content: '<div>This is a marker in ' + myloc + '</div>'
});
google.maps.event.addListener(markers[markers.length - 1], 'click', function() {
this['infowin'].open(map, this);
});
}
When all is done we basically attach window.onload event and call the initialize function:
window.onload = initialize;

Categories

Resources