I am using google maps on my website to display 2 locations. I want one map and for the map to update when I press a button for the different locations. This is the JS code.
var map;
var lat = 53.4779168;
var lng = -2.2338925;
function initMap() { map = new google.maps.Map(document.getElementById('map'), { center: { lat: lat, lng: lng }, zoom: 17 }); };
$(document).ready(function() {
$("#picadilly").click(function() {
lat = 53.4779168;
lng = -2.2338925;
});
$("#didsbury").click(function() {
lat = 53.410346;
lng = -2.229417;
});
});
It seems to be register that I'm pressing the button but it doesn't update the location of the map. Any ideas?
You can simply move the map with map.setCenter(LatLng) under click event function. This method will not use any other markers and will not erase existing markers. You could also move the map via the panTo(LatLng) function. Both methods are also available after the map has been initialized.
$("#picadilly").click(function() {
lat = 53.4779168;
lng = -2.2338925;
map.setCenter({lat:lat , lng:lng});
});
$("#didsbury").click(function() {
lat = 53.410346;
lng = -2.229417;
map.setCenter({lat:lat , lng:lng});
});
Here is the documentation for these methods.
Related
I have a list of links to several locations. I would like to add map marker to my OSM map and remove it when I hover out, while adding new one I hover over etc. I've been been able to add marker to the map on hover but I'm not able to remove them.
HTML
...
JS
function mkron(x) {
// some code to get lat lon
L.marker([lat, lon]).addTo(map);
}
function mkroff() {
markers.clearLayers();
}
What am I missing?
Your problem is that you add the marker directly to the map instead of adding it to the LayerGroup / FeatureGroup markers.
I don't know the rest of your code but it should look like that:
var markers = L.featureGroup().addTo(map);
function mkron(x) {
// some code to get lat lon
L.marker([lat, lon]).addTo(markers);
}
function mkroff() {
markers.clearLayers();
}
The other variant would be to store the layer in a global variable and then remove it from the map:
var marker;
function mkron(x) {
// some code to get lat lon
marker = L.marker([lat, lon]).addTo(map);
}
function mkroff() {
if(marker){
map.removeLayer(marker)
marker = null;
}
}
Here's my situation: I have a google sheet of coordinates that I want to map on a simple map. This map I want to put on a sidebar within google sheets. It will get more complex as I go but I'm struggling with the basics.
So I want to import the coordinates of C2:D2 into my HTML so I used this: google.script.run.withSuccessHandler(initMap).selectAddress().
It seems to work for most things but when I use it for the coordinates of the marker, nothing no marker shows up. If I replace
"var lat = CoordArray[0]; var lng = CoordArray[1];"
with
"var lat =51.0366961; var lng = -114.0744921;"
in the HTML, the marker shows up.
Even if I make "var CoordArray= [51.0366961,-114.0744921]" in the JS code, the marker still doesn't show. So the problem has something to do with transferring the information between the two pages.
I just want an interactive map sidebar that's based on coordinates from the sheet that I can kind of understand and modify.
So my JS code page looks like this:
function mapSidebar(){
var html = HtmlService.createHtmlOutputFromFile('Map.html')
.setTitle("Map Sidebar");
SpreadsheetApp.getUi().showSidebar(html);
};
//------------------------------------------------------------------------------------------------
function selectAddress(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName("maps?");
var CoordArray = sheet.getRange("C2:D2").getValues(); // C2:D2 = 51.0366961,-114.0744921
return CoordArray;
};
//----------------------------------------------------------------------------------------------
My Html page (Map.html) looks like this:
and yes, I replaced put my API key in the 'https://maps.googleapis.com/' link
<!DOCTYPE html>
<html>
<head>
<style>
#map {
height: 400px; /* The height is 400 pixels */
width: 100%; /* The width is the width of the web page */
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(CoordArray) {
var lat = CoordArray[0];
var lng = CoordArray[1];
var markerPosition = {lat: lat,lng: lng}
var map = new google.maps.Map(document.getElementById('map'), {
center:{lat: 51.0366961,lng: -114.0744921},
zoom: 8,
});
var marker = new google.maps.Marker({position: markerPosition, map: map});
}
google.script.run.withSuccessHandler(initMap).selectAddress();
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=MY_API_KEY=initMap">
</script>
</body>
</html>
It appears you may be having an issue with the Range.getValues() method in your code. This method returns a 2D array indexed by rows, then by columns.
Try in your initMap() function to get the "lat" and "lng" like so:
function initMap(CoordArray) {
var lat = CoordArray[0][0];
var lng = CoordArray[0][1];
var markerPosition = {
lat: lat,
lng: lng
}
var map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 51.0366961,
lng: -114.0744921
},
zoom: 8,
});
var marker = new google.maps.Marker({
position: markerPosition,
map: map
});
}
References:
Apps script docs Range.getValues()
I have this script to display markers on a google map, which works great but now I want to get current position to zoom in on map initially..
<body onload="initCoords()">
function initCoords() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
function showPosition(position) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
} // this gets the current location loaded when body loads //
How do I pass the lat and long into the map?
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(lat, long),
zoom: 12
});
</body>
It throws lat and long are not defined.
In the callback showPosition call the setPosition method of the map. As you have declared map within the initMap function perhaps declare the other functions also within the body of initMap
function initMap() {
lat=56;
long=-2;
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(lat, long),
zoom: 12
});
var initCoords=function() {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
var showError=function(e){
alert(e)
};
var showPosition=function( position ) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latlng=new google.maps.LatLng(lat,long);
map.setPosition( latlng );
/* add marker?? */
}
/* other code ?.... */
}/* close function*/
Or, declare use the callback function to initialise the map
var map,lat,long;
function initMap() {
var initCoords=function() {
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition(showPosition, showError);
}
}
var showError=function(e){
alert(e)
};
var showPosition=function( position ) {
var lat = position.coords.latitude;
var long = position.coords.longitude;
var latlng=new google.maps.LatLng(lat,long);
var map = new google.maps.Map( document.getElementById('map'), {
center: latlng,
zoom: 12
});
}
/* other code ?.... */
}/* close function*/
If you are loading the Google Maps JS API script asynchronously like so:
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap"
async defer></script>
then the body onload event will occur and call initCoords() before the maps API has fully been loaded. This means that any code inside that function that is trying to access the maps API will not work.
One option is to listen to the tilesloaded event of the map object and run the zoom-in function when that event is fired the first time (which happens when the visible tiles have finished loading).
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: 40, lng: 20},
zoom: 3
});
google.maps.event.addListenerOnce(map, 'tilesloaded', function() {
map.setZoom(8); // call initCoords()
});
}
I use addListenerOnce so that the map zooms in only after the first time the map's tiles have finished loading.
Here is a JSBin with this functionality.
I'm trying to send a few longitude and latitude variables to a function that will then generate a Google Map.
Starting with a datatable that retrieves various information stored in a database, I'm using data-attributes to store the lng and lat for each record. When a record is selected, a modal opens and the map is displayed.
I was able to get the map to display with default lng and lat points. But now I need to create a new map every time a record is selected.
Starting with the onclick event that triggers the modal to open (shortened as much as possible):
$('#example1').on('click', 'tr > td > a.actionMatch', function(e)
{
e.preventDefault();
var actimpbill = $(this).attr('data-actimpbill'); // random record info
var actramplat = parseFloat($(this).attr('data-actramplat')); // first lat
var actramplng = parseFloat($(this).attr('data-actramplng')); // first lng
var actdellat = parseFloat($(this).attr('data-actdellat')); // second lat
var actdellng = parseFloat($(this).attr('data-actdellng')); // second lng
// my map was opening in a grey box. this next piece of code fixed that
$("#actionMatchbackModal").on("shown.bs.modal", function () {
google.maps.event.trigger(map, "resize");
});
initMap(actramplat, actramplng, actdellat, actdellng); // my attempt to call a function and the variables to it
$('#actionMatchbackModal').modal('show'); // show the modal
});
Here is the function that sets the map. This is located outside of the initial onclick event that opens the modal (I'm not sure if that's a problem). This is where I'm trying to pass the variables that I created inside the onclick event:
function initMap(actramplat, actramplng, actdellat, actdellng)
{
// map options
var options = {
zoom: 8,
center: {actramplat, actramplng}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// add marker
var marker = new google.maps.Marker({
position:{actdellat, actdellng},
map: map
});
}
I am probably butchering the function call. The function once housed the default lat and lng numbers and I was able to properly generate a map.
Edit
I just checked the console, and I am getting these errors:
InvalidValueError: setCenter: not a LatLng or LatLngLiteral: in property lat: not a number
InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number
Edit
I just added parseFloat to the variables to ensure they are not strings, but still no success.
Edit
Here is what the data-attributes look like:
<a href="#" class="actionMatch" id="actionMatch"
data-toggle="modal" data-actimpbill="xxxxxxxx"
data-actramplat="39.11" data-actramplng="-94.63"
data-actdellat="39.03" data-actdellng="-96.83"
data-actreclat="39.84" data-actreclng="-96.65"
rel="tooltip" data-placement="right" title="Action Matchback"></a>
You can see the actramplat, actramplng, actdellat, actdellng in the A tag above.
Looking at their API, they expect lat/long values to be provided as an object literal that looks like this: var myLatLng = {lat: -25.363, lng: 131.044};
So you need to call it like this:
// map options
var options = {
zoom: 8,
center: {lat: dellat, lng: dellng}
}
// new map
var map = new google.maps.Map(document.getElementById('map'), options);
// add marker
var marker = new google.maps.Marker({
position:{lat: reclat, lng: reclng},
map: map
});
Using v.3 of the Google geocoder api with a Java back end, Velocity front end and an Oracle db.
Our current spec specifies that when a user selects a marker (lat/lng) that their zoom should be saved as well for future sessions. I can't for the life of me figure out how to do this. I have seen some information about bounds which I think I may be able to use in a hackey way, but I don't want to define the bounds of the map, I just want to save the zoom (like the lat/lng) and be able to pass it to the back end.
map.js
var geocoder;
var map;
var siteLocation;
var marker;
function initMap() {
var lat = parseFloat($("#newLat").val());
var lng = parseFloat($("#newLng").val());
geocoder = new google.maps.Geocoder();
siteLocation = { lat: lat, lng: lng };
map = new google.maps.Map(document.getElementById('map'),
{
center: siteLocation,
zoom: 19,
}
);
//set crosshair
console.log('setting waypoint marker');
crosshair = new google.maps.Marker(
{
position: siteLocation,
map: map,
draggable: false,
shape: { coords: [0, 0, 0, 0], type: 'rect' },
icon: "https://www.daftlogic.com/images/cross-hairs.gif"
}
);
crosshair.bindTo('position', map, 'center');
geocodeLatLng();
}
//use new selection to
function geocodeLatLng() {
var lat = crosshair.getPosition().lat();
var lng = crosshair.getPosition().lng();
var newLocation = crosshair.getPosition();
geocoder.geocode({ location : crosshair.position}, function(results, status) {
if (status == 'OK') {
results[0].geometry.location.lat();
results[0].geometry.location.lng();
} else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
//get new user selected map options, [drop marker] (optional)
$("#addGeolocation").on("click", function (evt) {
geocodeLatLng();
evt.preventDefault();
var newZoom = map.getZoom();
var newLat = crosshair.getPosition().lat();
var newLng = crosshair.getPosition().lng();
$("#newLat").val(newLat);
$("#newLng").val(newLng);
newLocation = new google.maps.LatLng(newLat, newLng);
map.setCenter(newLocation);
map.setZoom(newZoom);
//make sure no marker exists
if ( marker !== undefined) {
marker.setPosition(newLocation);
} else {
marker = new google.maps.Marker({
position: newLocation,
map: map,
draggable: true
});
}
});
Velocity Macro
#macro(map $ADDRESS)
<script defer
src="https://maps.googleapis.com/maps/api/js?key=${GOOGLE_API_KEY}&callback=initMap">
</script>
<div id="map"></div>
<span class="innerBlock smallBlock" id="map" ></span>
<button type="button" onclick="geocodeLatLng()" id="addGeolocation"> $BTN_ADD_GEOLOCATION</button>
#inp_hidden("newLat" "$context.getSite().getLatitude()")
#inp_hidden("newLng" "$context.getSite().getLongitude()")
#inp_hidden("newZoom")
#end
I am completely stumped. Any ideas? Most of the solutions I have seen involve cookies but we cannot use those. Any advice would be appreciated. Thanks!
I think I understand what you mean but correct me if I'm wrong.
You could save the zoom level in a variable.
var zoom = 16;
and then save this in the local storage
localStorage.setItem("zoomLevel", zoom);
then use getItem method to retrieve it
var savedZoom = localStorage.getItem("zoomLevel");
So if you were planning to have the zoom levels in a select box or something, you can save the users choice into the local storage and then retrieve it when they return by setting to zoom to 'savedZoom' for example.
I'm not completely sure if this is what you were after but hopefully it helps. I've tried not to go into too much detail just incase it isn't.