I'm trying to learn how to move a marker on the google map every x seconds (without refreshing the map or page ofcourse).
I have come across quite a few code and tutorials and questions on STO about moving or updating markers but they all want to do it via AJAX.
I don't want to do it via AJAX.
Basically, the lat/long of the marker gets stored in the localstorage();
So to move the marker every x seconds, I just need to look inside the localstorage as opposed to call AJAX etc etc...
The local storage looks something like this:
var lat = localStorage.getItem("mylat");
var lng = localStorage.getItem("mylng");
and the values of them are just simple string like so:
51.54647477
0.123383777
So, if I change any of those values locally (NO AJAX), I need teh marker to move or update its location so to speak.
First, is this even possible?
MAYBE, USING SETINTERVAL() ?!
If so, could someone please advise on this or point me in the right direction?
Any help would be greatly appreciated.
EDIT:
I think I'm getting somewhere. the issue is that the marker gets removed:
Here is a FIDDLE
If I use the lat/long values directly in the code the marker doesn't disappear in it moves but when I use the input value or localstorage valu, the marker disappears.
Works:
var NewLatLng = new google.maps.LatLng(20.371237, 72.90634);
Doesn't work:
var NewLatLng = new google.maps.LatLng(input);
Another EDIT:
This works now but it only moves the marker once and it wont move it again if I edit the inputs values:
http://jsfiddle.net/wduno9su/5/
This works fine now:
$(document).ready(function () {
var map;
function initialize()
{
var latlng = new google.maps.LatLng(21.16536,72.79387);
var myOptions = {
zoom: 5,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker
(
{
position: new google.maps.LatLng(21.1673643, 72.7851802),
map: map,
title: 'Click me'
}
);
var infowindow = new google.maps.InfoWindow({
content: 'Location info:<br/>SVNIT Post Office, Dumas Rd, Surat<br/>LatLng:<br/>21.1673643, 72.7851802'
});
google.maps.event.addListener(marker, 'click', function ()
{
infowindow.open(map, marker);
setTimeout(function(){infowindow.close();}, '5000');
});
//$('#clickme').on('click', function(){
setInterval(function() {
var input = $('#input').val();
var input2 = $('#input2').val();
var NewLatLng = new google.maps.LatLng(input, input2);
//setInterval(function() { marker.setPosition(NewLatLng);}, 2000);
marker.setPosition( NewLatLng );
});
}
window.onload = initialize;
});
One option would be to use setInterval to periodically read the localStorage and set the marker position (creating the marker if it doesn't exist).
proof of concept fiddle
code snippet:
var map;
var marker;
function initialize() {
map = new google.maps.Map(
document.getElementById("map_canvas"), {
center: new google.maps.LatLng(37.4419, -122.1419),
zoom: 13,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
}
function setLocalStorage() {
var lat = document.getElementById('lat').value;
var lng = document.getElementById('lng').value;
localStorage.setItem('mylat', lat);
localStorage.setItem('mylng', lng);
}
setInterval(function() {
var lat = parseFloat(localStorage.getItem("mylat"));
var lng = parseFloat(localStorage.getItem("mylng"));
map.panTo({
lat: lat,
lng: lng
});
if (!marker || !marker.setPosition) {
marker = new google.maps.Marker({
position: {
lat: lat,
lng: lng
},
map: map
});
} else {
marker.setPosition({
lat: lat,
lng: lng
});
}
}, 5000);
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<input id="lat" value="42" />
<input id="lng" value="-72" />
<input type="button" onclick="setLocalStorage();" value="click" />
<div id="map_canvas"></div>
Related
How do I add a user-input marker to Google Maps widget on my website, and get the latitude and longitude data from it?
Right now I am building an application which has to allow users to drop a marker to any location so that I can get that data and process it.
<script>
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 2,
center: new google.maps.LatLng(2.8,-187.3),
mapTypeId: 'terrain'
});
// Create a <script> tag and set the USGS URL as the source.
var script = document.createElement('script');
// This example uses a local copy of the GeoJSON stored at
// http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_week.geojsonp
script.src = 'https://developers.google.com/maps/documentation/javascript/examples/json/earthquake_GeoJSONP.js';
document.getElementsByTagName('head')[0].appendChild(script);
}
// Loop through the results array and place a marker for each
// set of coordinates.
window.eqfeed_callback = function(results) {
for (var i = 0; i < results.features.length; i++) {
var coords = results.features[i].geometry.coordinates;
var latLng = new google.maps.LatLng(coords[1],coords[0]);
var marker = new google.maps.Marker({
position: latLng,
map: map
});
}
}
</script>
Right now I am using this, but this doesn't offer any user submitted markers.
Try running this working jsfiddle for demonstration and guidance on how users can place markers on a Google map. Note that it's based off of Google's example on adding and removing markers.
Full JS code below:
var map;
var markers = [];
function initMap() {
var haightAshbury = {
lat: 37.769,
lng: -122.446
};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: haightAshbury,
mapTypeId: 'terrain'
});
// This event listener will call addMarker() when the map is clicked.
map.addListener('click', function(event) {
addMarker(event.latLng);
});
// Adds a marker at the center of the map.
addMarker(haightAshbury);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
markers.push(marker);
}
You can get the marker's coordinates from the map's click event listener, e.g.:
map.addListener('click', function(event) {
console.log(event.latLng.lat());
console.log(event.latLng.lng());
addMarker(event.latLng);
});
Or from the addMarker method:
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
console.log(marker.getPosition().lat());
console.log(marker.getPosition().lng());
markers.push(marker);
}
Hope this helps!
I have map which was set up on server and based on google map. To embeded it to my webpage I used iframe. Now i need to get lat and long on click to map and than write data to my db. How can i get it?
Here is my iframe
<iframe src="https://my_domain/projects/?first=7&second=123&third=567" width="100%" height="350px" align="left" id="inneriframe" scrolling="no"></iframe>
Here is no initialize or else function that usualy i use for google map, thats why can not get it by functions.
You can initialize the map on window.load and get the value using event addListener.
var map;
function initialize() {
var myLatlng = new google.maps.LatLng(24.18061975930,79.36565089010);
var myOptions = {
zoom:7,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("gmap"), myOptions);
// marker refers to a global variable
marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.addListener(map, "click", function(event) {
// get lat/lon of click
var clickLat = event.latLng.lat();
var clickLon = event.latLng.lng();
alert(clickLat.toFixed(5));
alert(clickLon.toFixed(5));
var marker = new google.maps.Marker({
position: new google.maps.LatLng(clickLat,clickLon),
map: map
});
});
}
window.onload = function () { initialize() };
My map is missing the pin drop, I tried figuring out the api page but i cant seem to get the pin on my google map. here is my code so far. If anyone has any ideas on how to get that pin on there I would appreciate it.
<!-- GOOGLE MAPS -->
<script src="https://maps.googleapis.com/maps/api/js?sensor=false"></script>
<script>
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(33.6676314, -117.6598071),
zoom: 14,
scrollwheel: false ,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options)
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<div id="map_canvas"></div>
That code is creating a map centered on lat 33.6676314, lng -117.6598071 and I'm pretty sure the map is showing fine. You haven't yet created any markers, so go on and make one. The code to achieve that, in its most basic form is
function initialize() {
var map_canvas = document.getElementById('map_canvas');
var map_options = {
center: new google.maps.LatLng(33.6676314, -117.6598071),
zoom: 14,
scrollwheel: false ,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(map_canvas, map_options);
var newmarker= new google.maps.Marker({
position: new google.maps.LatLng(33.6676314, -117.6598071),
map: map
});
}
please note that the map property of a marker should point to whatever variable you named your map to. For example:
var AwesomeMap = new google.maps.Map(map_canvas, map_options);
var newmarker= new google.maps.Marker({
position: new google.maps.LatLng(33.6676314, -117.6598071),
map: AwesomeMap
});
Position can be any valid LatLng object or LatLng literal. The following, for example, is valid too
var newmarker= new google.maps.Marker({
position: {lat:33.6676314, lng:-117.6598071},
map: AwesomeMap
});
Check this out
http://www.x2tutorials.com/tutorials/google-maps-v3/using-map-markers.php
If this is not what you are trying to achieve, please elaborate on the problem you are facing
Since yesterday I'm trying to add marker in Google Maps Api v3 . I read the documentation and all. Here's my code :
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(28.63, 77.21),
zoom: 8,
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
}
// google.maps.event.addDomListener(window, 'load', initialize);
function getFillingDetails(){
var vehicleId = $('#selectVehicle option:selected').val();
$.getJSON('getFillingDetails.php', {id : vehicleId}, function(data){
var lat = [];
var lon = [];
var price = [];
$.each(data, function(key, value){
lat.push(value.latitude);
lon.push(value.longitude);
price.push(value.price);
});
});
var myLatlng = new google.maps.LatLng(23.72,77.10);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map,
});
}
</script>
Everything looks fine to me. The initialize() function is called after onload of body tag.
And getFillingDetails() function is called when I click a button.
But still I'm getting no success.
You have a syntax error at:
var marker = new google.maps.Marker({
position: new google.maps.LatLng(23.72, 72.100),
map: map, <--- get rid of this comma
});
next time you should look in the developer console for any errors.
// To add the marker to the map, call setMap();
marker.setMap(map);
source : https://developers.google.com/maps/documentation/javascript/markers
I am going to need at least 3 maps on the same page (one below the other, not side by side), each containing multiple markers. Can anyone tell me how to get three versions of this on the same page (after which I can amend the details for each one)? I'm basically feeling my way here, not knowing much about javascript.
Many thanks in advance - Roger
<div id="map" style="height:400px;width:541px;display:block;">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function mapIt(){
var latlng = new google.maps.LatLng(24.00, 0.00);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('map'), myOptions);
setMarkers(map, places);
}
var places = [
['London',51.50, -0.125,"Markers/green.png"],
['Abidjan',5.34, -4.03,"Markers/red2.png"],
['Abu Dhabi',24.47, 54.37,"Markers/red2.png"],
];
var popUps = [
'<strong>London</strong><br />link to larger map',
'<strong>Abidjan, Ivory Coast</strong><br />Content here',
'<strong>Abu Dhabi, United Arab Emirates</strong><br />Content here>',
]
var infowindow;
function setMarkers(map, locations) {
for (var i = 0; i < places.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
var icon = locations[i][3];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: locations[i][0],
icon: icon
});
(function(i, marker) {
google.maps.event.addListener(marker,'click',function() {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(popUps[i]);
infowindow.open(map, marker);
});
})(i, marker);
}
};
mapIt();
</script></div>
I few minutes ago created code which shows how to set four maps in the same page.
See it from JS Fiddle
It basically just boils down to setting correct number of div elements for maps:
<div id="map0"></div>
<div id="map1"></div>
<div id="map2"></div>
<div id="map3"></div>
and initializing them:
var map0 = new google.maps.Map(document.getElementById("map0"), mapOptions);
var map1 = new google.maps.Map(document.getElementById("map1"), mapOptions);
var map2 = new google.maps.Map(document.getElementById("map2"), mapOptions);
var map3 = new google.maps.Map(document.getElementById("map3"), mapOptions);
Edit:
I updated example to add markers to following kind of object so they are easier to be accessed based on what map markers you want to handle.
var markers = {
'map0' : [],
'map1' : [],
'map2' : [],
'map3' : [],
};
It should print following debug information to javascript console:
Marker is: (60.12816100000001, 18.643501000000015) map name is: map0
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (61.92410999999999, 25.748151000000007) map name is: map1
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (32.7151137, -117.15665719999998) map name is: map2
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (35.86166, 104.19539699999996) map name is: map3
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
So in the example I provided I only add one marker per map, but add as many as you like since markers object has array for each map type.
Cheers.