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.
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'm working with google maps api and javascript which I am not much familiar with. Here's the code I use to draw markers on my map. I get Latitudes and Longitudes from my database:
var geocoder;
var map;
var jsonStr = '<?php echo json_encode($arajka) ?>';
var LatLong = JSON.parse(jsonStr);
function initialize() {
geocoder = new google.maps.Geocoder();
var mapOptions = {
center: new google.maps.LatLng(50.000001, 20.000001),
zoom: 12
};
map = new google.maps.Map(document.getElementById("map-canvas"),
mapOptions);
var marker = [];
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login}));
}
// trying to set some listener but it fails.
google.maps.event.addListener(marker, 'click', function() {
map.setZoom(8);
map.setCenter(marker.getPosition());
alert("ASDASDASD" + marker.ajdi);
});
}
So, this listener doesn't work, I don't know why. Well, I expect that it doesn't exactly know what marker is it about. When I tried to do it with a single one, like in tutorial, it worked properly. I don't know what to do when I have this array. Any suggestions please?
You have several mistakes in your code:
As #Hollister mentions, marker is an array, so you need to put the addListener call inside the loop;
You have to store the additional marker data into the marker, not into the marker array;
you have to use this in the listener, not marker.
for(var i=0;i<LatLong.length;i++){
var LatLong1 = new google.maps.LatLng(LatLong[i].lat, LatLong[i].lon);
var this_marker = new google.maps.Marker({position: LatLong1, map: map, title: LatLong[i].login});
this_marker.ajdi=LatLong[i].id; // storing additional data (I need to get it when user clicks on certain marker)
marker.push(this_marker);
// trying to set some listener but it fails.
google.maps.event.addListener(this_marker, 'click', function() {
map.setZoom(8);
map.setCenter(this.getPosition());
alert("ASDASDASD" + this.ajdi);
});
}
I'm trying to show markers on my map. but it's not showing them.
this is the code I use:
var map;
var markers = new Array();
function initialize() {
var mapOptions = {
zoom: 12,
center: new google.maps.LatLng(27.9881, 86.9253),
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
google.maps.event.addListener(map, 'click', addMarker);
}
function addMarker(event) {
markers.push(event.latLng);
marker = new google.maps.Marker({
position: event.latLng,
map: map
});
console.log(markers);
}
google.maps.event.addDomListener(window, 'load', initialize);
the console is logging on every click an new coordinate, so the function is called, and coordinates are passed. And I can't really see any problems in the marker code.
So can anyone see the problem?
map is a local variable, only visible inside initialize.
Use this instead of map when you set the map-property of the marker:
function addMarker(event) {
markers.push(event.latLng);
marker = new google.maps.Marker({
position: event.latLng,
map: this
});
}
Explanation:
the callback will be executed in the scope of the object that triggers the event. Here it is the Maps-instance(because the click-listener has been applied to the map ), this will refer to this object inside the callback.
markers.push(event.latLng);
Here you're pushing the latlng, not the marker.
markers is an array variable with global scope, whereas marker is a local variable.
In markers array you have to insert each inidividual marker and then process it.
function addMarker(event) {
var marker = new google.maps.Marker({
position: event.latLng,
map: map
});
markers.push(marker);
}
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.
I have the following code that allows a user to click somewhere on the map and it records the GPS location of wherever they click. It works properly on the backend but whenever the user clicks more than once it leaves multiple markers on the map. It always keeps whatever the last location is so it works but it is somewhat confusing for the user who doesn't know what is going on on the backend. Is there some little trick I can do to make it so that whenever the user clicks to create a new marker the old one is removed?
code:
var map;
var GPSlocation;
function initialize() {
var haightAshbury = new google.maps.LatLng(37.7699298, -93.4469157);
var mapOptions = {
zoom: 4,
center: haightAshbury,
mapTypeId: google.maps.MapTypeId.TERRAIN
};
map = new google.maps.Map(document.getElementById("map"), mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
addMarker(event.latLng);
});
}
function addMarker(location) {
//I save the location right here
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
Just use setPosition method of google.maps.Marker instance:
var map,
GPSlocation,
marker; // <-- Added
// ... snip ...
function addMarker(location) {
// ... snip ...
if (!marker) {
// Create the marker if it doesn't exist
marker = new google.maps.Marker({
position: location,
map: map
});
}
// Otherwise, simply update its location on the map.
else { marker.setPosition(location); }
}
Make the marker a global variable by declaring it outside your function:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
marker = new google.maps.Marker({
position: location,
map: map
});
}
You can also make it more efficient by only updating the location of the marker rather than creating a new object:
var marker;
function addMarker(location) {
GPSlocation = location;
document.getElementById("GPSlocation").value = GPSlocation;
if (!marker) {
marker = new google.maps.Marker({
position: location,
map: map
});
} else {
marker.setPosition(location);
}
}