Markers not showing on google maps - javascript

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

Related

dynamically adding markers to google map on click

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.

Google Maps overlay wont position over correct markers

I'm trying to make a list of markers to pin onto a map, each having its own overlay. It's mostly working, however the overlays are all being positioned over the top of one another instead of its corresponding marker.
Code is as follows:
var myCenter = getMyLocation();
function initialize()
{
var mapProp = {
center: myCenter,
zoom:9,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var locations = [
{lat: -27.646670, lng: 152.86918630, text: 'Address #1'},
{lat: -27.6446550, lng: 152.7822390, text: 'Address #2'},
{lat: -27.6062480, lng: 152.7889550, text: 'Address #3'}
];
// Loop through our list and plot them on the map
locations.forEach(function (l) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(l.lat, l.lng),
});
marker.setMap(map);
// Create our infoWindow panel for our marker
var infoWindow = new google.maps.InfoWindow({
content: l.text
});
// Bind click event for our marker
google.maps.event.addListener(marker, 'click', function () {
infoWindow.open(map, marker);
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I have a feeling that the issue is something to do with the on click addListener event
You're simply missing a var:
marker = new google.maps.Marker(...
should be:
var marker = new google.maps.Marker(
As a result, you only have a single global marker variable instead of a unique one for each marker as you should.
Since you're using .forEach with a callback function, that callback function provides you with a closure for each iteration of the loop. So all you need is to take advantage of that closure by making marker a local variable inside the callback.
Maybe closure will help you? Marker is an object, because of it on every loop link to it changes. Closure will prevent it.
google.maps.event.addListener(marker, 'click', (function(marker){ return function () {
infoWindow.open(map, marker);
};})(marker));

Showing additional marker in google map through ajax

I have created a google map using "maps.googleapis.com/maps/api/js?v=3". In that map I am showing markers for different locations, which is working fine. Below is the code which i have used.
google.maps.event.addDomListener(window, 'load', function() {
var map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
});
Now I want to add some more location markers in Ajax. For ex: I will add the location name from a dropdown, it will do an ajax call to the server side. Pull out the location latitude and longitude and will show in the map. How can i achieve it.
I have written a separate js function to do the ajax call, but inside that the code is not getting 'map' instance.Here I have used only this code
new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
Here I am not initializing the map again. So its not getting the map instance and throwing error. How to fix it.
The scope of your map is limited to inside your event handle. Try this:
var map, markerCollection;
google.maps.event.addDomListener(window, 'load', function() {
map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
});
function addMarker(lat, lng){
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(lat, lng),
});
markerCollection.push(marker);
}
NOTES:
1) Be to fill in the values for "latitude" and "longitude" when defining the center of your map. Otherwise you just would get a map displayed.
2) I know it might not be the best practice to add your markers into an array but I find this makes than easy to access latter.
Since map is not a global variable it is getting dereferenced. Make the map object either global or within a container function that stores all of your code.
Global JS example
//now it's global
var map;
google.maps.event.addDomListener(window, 'load', function () {
map = new google.maps.Map(document.getElementById('map1'), {
zoom: 10,
center: new google.maps.LatLng(latitude, longitude),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(23.42323, -45.47653),
});
});

Allow user to create only one Google Maps marker at a time

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

google maps API v3 set marker and get point

I have a problem to set marker and get latitude and longitude for that marker. How can I do that in google maps v3 API
var myLatlng = new google.maps.LatLng(-34.397, 150.644);
var myOptions = {
zoom: 8,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("divGoogleMaps"), myOptions);
google.maps.event.addListener(map, 'click', function() {
});
this is my start code.
You should check Google Maps API doc web-site they have a fex example to help you started.
http://code.google.com/apis/maps/documentation/javascript/basics.html
google.maps.event.addListener(map, 'click', function(e) {
placeMarker(e.latLng, map);
});
}
function placeMarker(position, map) {
var marker = new google.maps.Marker({
position: position,
map: map
});
map.panTo(position);
}
Here you set a marker and get the position.
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title:"Hello World!"
});
Taken directly from Google Maps API v3
If you want to attach an event listener to the marker, it is advisable to do it right after you add it to the map, while you still have a fresh reference to it (in the case where you're potentially looping through some marker adding code, as is common).

Categories