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
});
Related
I need to use the location a marker is placed to be able to load weather data via another API. I have my map dropping a loading and dropping a marker as well as a object "myPosition" which should contain the lat and lon of the marker. My issue is getting the myPosition.lat and .lng to update with the coordinates of the marker. Below is the code I have thus far and I am able to get the initialized data from myPosition in another file but I cant figure out how to get the coordinates. This is my first time using HTML and JS and I usually use C++ or Java so its a bit of a change for me.
var myPosition =
{
lat: 0,
lng: 0
};
function initMap()
{
var texas = {lat: 32.7767, lng: -96.7970};
var map = new google.maps.Map(document.getElementById('map'),
{
zoom: 10,
center: texas
});
var marker = new google.maps.Marker({
position: texas,
map: map
});
google.maps.event.addListener(map, 'click', function(event)
{
placeMarker(event.latLng);
});
function placeMarker(location)
{
if (marker == undefined)
{
marker = new google.maps.Marker(
{
position: location,
map: map,
animation: google.maps.Animation.DROP,
});
}
else
{
marker.setPosition(location);
}
map.setCenter(location);
}
}
Sounds like what you need is to think about the problem less as your 'other file' accessing the coordinates, and more as notifying your other module that a mouse click on the map has occurred by means of a callback.
Eg. In weather.js
function handleCoords(latlng){
//...Do whatever you want with latlng
}
// Export function as needed if you're using modules/webpack.
// (don't worry if you don't know what this means)
Then in your main.js in your embedded HTML embedded JS
// import {handleCoords} from './weather'
// Again ignore this if you're not using modules/don't know what this means.
google.maps.event.addListener(map, 'click', function(event){
placeMarker(event.latLng);
handleCoords(event.latLng); // This is how you pass the latlng
// along to weather.js
});
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.
I am trying to create a website that has a google map in one column and in the second is a list of items with location elements. On clicking one of these items, I would like to drop a pin in the google map. I am having trouble updating the markers on the google map. I can add one marker at initialization of the map, but cannot get new markers to be dropped. Here is my code: https://gist.github.com/aarongirard/32f80f17e19d3e0389da. The issue occurs in the if else clause within the click function.
Any help is appreciated!!
//global variables //google map
var map;
var marker;
var currentMakerli;
function initialize() {
//set latlng of starting window of map
var mapOptions = {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
};
//set map using above options and attach to given element
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//construct new marker; constructor takes an object with position and title properties
//get lat long for first marker
var latlng = new google.maps.LatLng(34.073514, -118.562348);
marker = new google.maps.Marker({
position: latlng,
map: map,
title: "Home"
});
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
//if current marker set to this already
//remove marker
if ( $(this).attr('id') === 'current') {
marker.setMap(null);
$(this).attr('id', '');
} else {
$(this).attr('id','current');
var latlngarr = getLatLngFromString($(this).attr('data-position'));
var lat = latlngarr[0];
var lng = latlngarr[1];
thisLatlng = new google.maps.LatLng(lat,lng);
var marker = new google.maps.Marker({
position: latlng,
map: map,
});
//marker.setMap(map);
}
});
}
//set map
google.maps.event.addDomListener(window, 'load', initialize);
function getLatLngFromString(string){
var array = string.split(',');
array[0] = parseFloat(array[0]);
array[1] = parseFloat(array[1]);
return array;
}
You must store the marker in a way in which you are able to get a relation between the <li> and the marker, e.g. via $.data
simple example:
function initialize() {
//set latlng of starting window of map
var map = new google.maps.Map($('#map-canvas')[0], {
center: { lat: 34.073609, lng: -118.562313},
zoom: 14,
disableDefaultUI:true
}),
home = new google.maps.Marker({
position: { lat: 34.073514, lng: -118.562348},
map: map,
title: "Home",
icon:'http://maps.google.com/mapfiles/arrow.png'
});
map.controls[google.maps.ControlPosition.TOP_LEFT].push($(".DataList")[0]);
//on click of li add new marker or remove if marker already exists
$(".DataList li").click(function(){
var that=$(this);
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
var marker=that.data('marker');
//simply check the markers map-property to decide
//if the marker has to be added or removed
if(marker.getMap()){
that.removeClass('current');
marker.setMap(null);
}
else{
that.addClass('current');
marker.setMap(map);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html,body,#map-canvas{height:100%;margin:0;padding:0}
.current{background:#f1f1f1;}
.DataList{background:#fff;padding:0;}
.DataList li{cursor:pointer;padding:4px;list-style-position:inside;}
<script src="https://code.jquery.com/jquery-latest.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3"></script>
<ul class="DataList">
<li data-position="34.0717825, -118.567396">Santa Ynez Canyon Park</li>
<li data-position="34.0787989, -118.572502">Palisades Country Estates</li>
<li data-position="34.078375, -118.56098">Highland Recreation Center</li>
</ul>
<div id="map-canvas"></div>
Related to the comments:
You didn't mess up with variable-names, my examples uses less variables, but you may use more variables when you want to.
I prefer to avoid variables when I need to access an object only once.
The marker will be created here(and stored as a property of the <li/>):
//when there is no marker associated with the li we create a new
if(!that.data('marker')){
that.data('marker',new google.maps.Marker({position:(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))}));
}
The part that splits the data-position-attribute is this:
(function(ll){
return new google.maps.LatLng(ll[0],ll[1]);
}(that.data('position').split(/,/)))
It's a so-called "self-executing anonymous function", which returns the desired value(a LatLng) which will be used as position of the Marker. The splitted data-position-attribute will be used as argument for this function
that.data('position').split(/,/)
getMap() returns whatever the map-property has been set to, either a google.maps.Map-instance or null (when you want to remove the marker or when the property is not set). Although it's not a boolean value it evaluates to either true(when it's a map) or false(when it's null), so it may be used as condition.
The that-variable is always a new variable, that's correct, but it will always be a reference to the same object, the clicked <li/>. The marker has been stored as property of this object.
I have a database of locations which I want to be able to print on a map. Ideally there should be one map with multiple pins for each location you have toggled on. So click a button for location X and it shows up on the map. Click the button for location Y and it shows up on the same map. Click X again and it hides from the map.
Currently I have it so I click on X and the map gets redrawn centered around point X.
Here is the HTML for each button:
<input type='button' data-lat='38.89864400' data-long='-77.05283400'
data-when='20 Aug at 2:00am' value='Location X' class='click' />
The jQuery I'm using is:
jQuery(document).ready(
function initialize() {
jQuery("input.click").click(function() {
showOnMap(jQuery(this).data('lat'), jQuery(this).data('long'), jQuery(this).data('when'));
});
}
);
function showOnMap(lat, long, message) {
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 13,
center: myLatlng
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: message
});
google.maps.event.addDomListener(window, 'load', showOnMap);
}
Is there an easy way to switch from what I have to what I want? I've searched for a while but no one seems to be asking this use case in a browser, just Android (which I'm not doing).
Thanks!
There is an example in the documentation on how to hide/show markers. In short, a marker is:
hidden by setting its map to null
showed by setting its map to map
To do so, you will need to access each marker individually. If you have a definite number of locations, it can be done by naming them with different names (eg var markerLocationX, var markerLocationY, etc). Otherwise, the markers need to be stored in an array.
Supposing you have a definite number of known locations to toggle the markers, your javascript code may look like this:
function toggleMarker(markerName) {
if (markerName.getMap() == null) {
markerName.setMap(map);
} else {
markerName.setMap(null);
}
}
I have an html table that contains 10 container for Google map
Below is the js function that create the map object
Function takes the lat and the lng of the map + the div element to insert the map to.
function GetMap(lat,lng,number)
{
var show_in=document.getElementsByClassName("map_conteiner")[number];
var mapOptions = {
center: new google.maps.LatLng(lat, lng),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(show_in,
mapOptions);
var marker = new google.maps.Marker({
position:new google.maps.LatLng(lat,lng),
map: map,
title:"Hotel"
});
$(show_in).fadeIn();
}
The problem is that the map is displayed correctly only on the first invoke of this function
(No matter which div I start with)
after the firts invoke this function will allways present distorted maps (As you can see in the attached picture)
You should trigger the resize-event of the map in the complete-callback of $.fadeIn()
Furthermore you better create only 1 maps-instance for each map_conteiner and on subsequent calls of GetMap only set the new center of the existing map and the new position for the marker.