Google maps marker not showing up javascript - javascript

I'm trying to add a marker to my google map within my HTML project. The map centres on the exact coordinates I like and is perfect except the marker I've added doesn't show up at all. I've followed the documentation but to no success.
var google;
function init() {
var myLatlng = new google.maps.LatLng(40.69847032728747, -73.9514422416687);
var mapOptions = {
// How zoomed in you want the map to start at (always required)
zoom: 7,
// The latitude and longitude to center the map (always required)
center: myLatlng,
// How you would like to style the map.
scrollwheel: false,
styles: [
{
"featureType": "administrative.country",
"elementType": "geometry",
"stylers": [
{
"visibility": "simplified"
},
{
"hue": "#ff0000"
}
]
}
]
};
I'm using a div with id="map" seen below
var mapElement = document.getElementById('map');
var map = new google.maps.Map(mapElement, mapOptions);
var addresses = ['New York'];
for (var x = 0; x < addresses.length; x++) {
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false', null, function (data) {
var p = data.results[0].geometry.location
var latlng = new google.maps.LatLng(p.lat, p.lng);
new google.maps.Marker({
position: latlng,
map: map,
title: 'NY'
});
});
}
}
google.maps.event.addDomListener(window, 'load', init);

You have to add your API key.
$.getJSON('http://maps.googleapis.com/maps/api/geocode/json?address='+addresses[x]+'&sensor=false&key=ADD_YOUR_API_KEY', null, function (data) {
Check this out!
https://developers.google.com/maps/documentation/geocoding/intro#GeocodingResponses

Related

How can I customize the map and remove the 'POI Layer'?

On the embedded Google map (e.g. here - https://www.familienfreunde.de/4.php?Nummer=132700000302) you can see a lot of Point of Interest.
I would like to remove them.
<script>
function initMap() {
var latlng = new google.maps.LatLng(51.3267379,12.3653812);
var myOptions = {
zoom: 19,
center: latlng,
mapTypeControlOptions: {
mapTypeIds: ["roadmap", "satellite"]
}
};
map = new google.maps.Map(document.getElementById("map"), myOptions);
var box_html = "<h5>Gymnasium Gerda Taro Schule</h5><p>04107 Leipzig<br /><b>Profil anzeigen</b></p>";
var icon = new google.maps.MarkerImage('/bilder/marker4.png');
var marker = add_marker(51.3267379,12.3653812,'Gymnasium Gerda Taro Schule',box_html,icon);
marker.setMap(map);
var box_html = "<h5>Rechtsanwalt Henry Bach</h5><p>04107 Leipzig<br /><b>Profil anzeigen</b></p>";
var icon = new google.maps.MarkerImage('/bilder/marker22.png');
var marker = add_marker(51.3339224,12.3741322,'Rechtsanwalt Henry Bach',box_html,icon);
marker.setMap(map); }
function add_marker(lat,lng,title,box_html,icon) {
var infowindow = new google.maps.InfoWindow({
content: box_html
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
map: map,
icon: icon,
title: title
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
google.maps.event.addListener(map, 'dragstart', function() {
infowindow.close();
});
return marker;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=UNSERKEY&callback=initMap" async defer></script>
(I have only removed some more markers for the sake of clarity.)
You could try seeting the visibility of POI off using styles property
function initMap() {
var latlng = new google.maps.LatLng(51.3267379,12.3653812);
var myOptions = {
zoom: 19,
center: latlng,
styles = [
{
featureType: "poi",
elementType: "labels",
stylers: [
{ visibility: "off" }
]
}
];
mapTypeControlOptions: {
mapTypeIds: ["roadmap", "satellite"]
}

Google Maps API - Toggle Marker Visibility

How do I toggle the visibility of a subset of markers in Google Maps API?
I have two sets of marker location data. Want to add a button to toggle visibility of each set independently.
Full code below for convenience. I have a button code in the header.
<button onclick="toggleMELocations()">Toggle ME Locations</button>`
The button is showing up, but clicking does not yield the expected result (ME locations disappearing).
The relevant function is "toggleMELocations." I am trying to say that if ME locations are currently visible, make them invisible. And vice versa.
Any help is much appreciated.
var map;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {
lat: 40,
lng: -95
},
styles: [{
stylers: [{
saturation: -100
}]
}]
});
setMarkers(map);
}
function toggleMELocations() {
if (MEs) {
for (i in MEs) {
var visibility = (MEs[i].getVisible() == true) ? false : true;
MEs[i].setVisible(visibility);
}
}
}
// MEC locations
var MEs = [
['aaa', 36.07, -75.79],
['bbb', 40.07, -83.79]
];
// CC locations
var Concentras = [
['xxx', 38.01, -75.55],
['yyy', 30.10, -90.3]
];
function setMarkers(map) {
// Adds markers to the map.
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
}
for (var i = 0; i < Concentras.length; i++) {
var Concentra = Concentras[i];
var marker = new google.maps.Marker({
position: {
lat: Concentra[1],
lng: Concentra[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/red-dot.png',
map: map,
title: Concentra[0]
});
}
}
Firstly getVisible() is not a valid function.
You need to add a global variable defined: var addedMEs = [];
This acts as an array of markers that have been added to the map in the setMarkers method. We change the setMarkers method to include a line which will add a marker object to the array defined above:
for (var i = 0; i < MEs.length; i++) {
var ME = MEs[i];
var marker = new google.maps.Marker({
position: {
lat: ME[1],
lng: ME[2]
},
icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png',
map: map,
title: ME[0]
});
addedMEs.push(marker);
}
Then we need to remove the getVisible() method as it is invalid. we change this line to:
var bounds = map.getBounds();
var visibility = (bounds.contains(addedMEs[i].position) == true) ? false : true;
addedMEs[i].setVisible(visibility);
And it works. :]
Here is the JSFiddle to try: https://jsfiddle.net/cmjcs5eL/13/

Recenter map with multiple markers

I display multiple markers on a map. The list of locations is built with PHP:
$myData .= '["'.$Name.'", '.$lat.', '.$blon.'],';
Then I use JS to plot markers on the map.
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {lat: 32.99999999, lng: -95.2222328}
});
setMarkers(map);
}
var stores = ['.$myData.'];
function setMarkers(map) {
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
}
}
I need to re-center the map on map load. Should I try to average lat/lon coords from $myData array and replace center coords in initMap or is there a better way?
In this story: It's better to get average lat/long coordinates from the back-end (or calculate it on a front-end, but before you initialize a GoogleMap), so your map will be loaded in the right place and will not "tremble".
But you still may have a problem with zooming, and there are a few solutions. Most difficult is calculate again, but maybe you can try something of it (and it may make an interesting effect on page loading):
A. Zoom in from the space. Set smallest zoom and after google.API calculates bounding box — zoom in!
B. Show preloader screen over the map. In this case, you can calculate average lat/long using google.API too. It's the easiest way, but not so smooth and cool.
create an empty bounds object (a google.maps.LatLngBounds)
add all your markers to it
use it to center and zoom your map
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {lat: store[1], lng: store[2]},
map: map,
title: restaurant[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById("map"), {
zoom: 12,
center: {
lat: 32.99999999,
lng: -95.2222328
}
});
setMarkers(map);
}
var stores = [
["store 1", 42, -72],
["store 2", 41, -74]
];
function setMarkers(map) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < stores.length; i++) {
var store = stores[i];
var marker = new google.maps.Marker({
position: {
lat: store[1],
lng: store[2]
},
map: map,
title: store[0]
});
bounds.extend(marker.getPosition());
}
map.fitBounds(bounds);
}
google.maps.event.addDomListener(window, "load", initMap);
html,
body,
#map {
height: 100%;
width: 100%;
margin: 0px;
padding: 0px
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
<div id="map"></div>
Here is how I do it (a small snippet of my code) in jQuery, just pass your map into the function:
function (mapInfo) {
var noMarkers = false;
if (!mapInfo.markers || mapInfo.markers.length === 0) {
noMarkers = true;
var marker = new google.maps.Marker({
position: { lat: YOUR_DESIRED_HOME_POINT, lng: YOUR_DESIRED_HOME_POINT },
optimized: false
});
mapInfo.markers.push(marker);
}
var bounds = new google.maps.LatLngBounds();
// Create bounds from markers
$.each(mapInfo.markers, function (index, item) {
var latlng = mapInfo.markers[index].getPosition();
bounds.extend(latlng);
});
// Google wants to zoom ALL the way in for only one marker, so if there is only one, we'll back it out a bit
if (bounds.getNorthEast().equals(bounds.getSouthWest())) {
var adjustBy = noMarkers ? 20.5 : 0.005;
var extendNortheast = new google.maps.LatLng(bounds.getNorthEast().lat() + adjustBy, bounds.getNorthEast().lng() + adjustBy);
var extendSouthwest = new google.maps.LatLng(bounds.getNorthEast().lat() - adjustBy, bounds.getNorthEast().lng() - adjustBy);
bounds.extend(extendNortheast);
bounds.extend(extendSouthwest);
}
google.maps.event.addListenerOnce(mapInfo.map, 'bounds_changed', function () {
var zoom = mapInfo.map.getZoom();
if (zoom > 18) {
mapInfo.map.setZoom(16);
}
});
mapInfo.map.fitBounds(bounds);
}

Multiple FusionTables Queries Not Working

I am using Google Maps API. I want to assign colors to some countries.
To do that, i have to get each country boundaries to be able to draw polygon. So, i'm using FusionTables. For every countries, I do FusionTables query to get the layer and then set the map. Here what i have done.
var countryArray = new Array();
var nodeArray = new Array();
var companyArray = new Array();
var locationsArray = new Array();
function plotMarker() {
var rootMarker = locationsArray[companyArray.indexOf(rootCompany)];
var latlng = new google.maps.LatLng(0, 0);
var myStyle = [
{
featureType: "all",
elementType: "labels",
stylers: [
{
visibility: "off" }
]
}
];
map = new google.maps.Map(document.getElementById("map_canvas"), {
mapTypeControlOptions: {
mapTypeIds: ['mystyle', google.maps.MapTypeId.ROADMAP, google.maps.MapTypeId.TERRAIN]
},
center: latlng,
zoom: 2,
mapTypeId: 'mystyle'
});
map.mapTypes.set('mystyle', new google.maps.StyledMapType(myStyle, { name: 'My Style' }));
for (var i = 0; i < locationsArray.length; i++) {
if (locationsArray[i] != undefined) {
var latitude = locationsArray[i].lat() + verDiff;
var longitude = locationsArray[i].lng() + horDiff;
var newLatlng = new google.maps.LatLng(latitude, longitude);
var ftoptions = {
query: {
from: '419167',
select: 'kml_4326',
where: "sovereignt = '"+countryArray[i]+"'"
},
suppressInfoWindows:true,
styles: [
{
polygonOptions: {
fillColor:'#0040FF',
fillOpacity:0.7
}
}
]
};
var layer = new google.maps.FusionTablesLayer(ftoptions);
layer.setMap(map);
}
}
}
But, why does the style only work for the first country? I wonder if the queries are not successfully performed for all countries or just there's something wrong with the style? Any helps would be appreciated.
A map can only have 1 styled FusionTablesLayer, the styles of the other layers will be ignored.
Create a single FusionTablesLayer and select multiple sovereignt's via a IN()-condition

Google Maps v3 - Markers not displaying

I am trying to place multiple markers on a Google Map (API v3). I looked at the Google docs and also this thread. The map draws and centers to the init point but no markers are showing on the map.
Firebug is not reporting any errors.
Here is the JS
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
//Add 1st marker
var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
var marker_0 = new google.maps.Marker({
position: Latlng_0,
title:"0"});
marker_0.setMap(map);
//Add 2nd marker
var Latlng_1 = new google.maps.LatLng(41.065294480291,-85.330151019708);
var marker_1 = new google.maps.Marker({
position: Latlng_1,
title:"1"});
marker_1.setMap(map);
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Thanks for looking!
The reason the markers are not showing up is because that part of the code is getting executed before the load event gets fired and the initialize method gets invoked - at that point your map variable is already created but is still null.
try adding the code to add the markers inside the initialize method
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(41.056466,-85.3312009),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
// Add 1st marker
var Latlng_0 = new google.maps.LatLng(41.057814980291,-85.329851919709);
var marker_0 = new google.maps.Marker(
{
position: Latlng_0,
title:"0"
}
);
marker_0.setMap(map);
//Add 2nd marker
var Latlng_1 = new google.maps.LatLng(41.065294480291,-85.330151019708);
var marker_1 = new google.maps.Marker(
{
position: Latlng_1,
title:"1"
}
);
marker_1.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
see this jsfiddle here where the markers are showing up http://jsfiddle.net/KvugB/
I use this code. I hope it helps you:
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(41.056466, -85.3312009),
disableDefaultUI: false,
zoom: 16,
mapTypeId: google.maps.MapTypeId.SATELLITE
});
// Creating the JSON data
var json = [
{
"title": "Title 1",
"lat": 41.057814980291,
"lng": -85.329851919709,
"description": ""
},
{
"title": "Title 2",
"lat": 41.057814981000,
"lng": -85.8048,
"description": ""
},
]
var styles = [
{
"featureType": "water",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "color": "#0077bb" },
{ "lightness": 70 }
]
},{
"featureType": "landscape.natural",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "saturation": -100 },
{ "color": "#699e6b" },
{ "lightness": 76 }
]
},{
"featureType": "poi.park",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "off" }
]
},{
"featureType": "road.local",
"elementType": "geometry.fill",
"stylers": [
{ "visibility": "on" },
{ "color": "#ffffff" }
]
}
];
map.setOptions({styles: styles});
// Creating a global infoWindow object that will be reused by all markers
var infoWindow = new google.maps.InfoWindow();
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
}
})();
This is a reply to #JoanManuelHernández's answer, but I can't post formatted code in a comment.
Joan, your solution is excellent; it's very similar to how I would do it myself. Creating an array of marker locations is way better than using individual variables for each one.
I'd like to suggest a couple of minor improvements. One is where you have the array named json. That isn't a very descriptive name; json could mean any kind of data. How about calling it something like places or locations or the like?
Next, where you have the loop that creates the closure to handle the asynchronous callback, I think it's a bit easier to understand how it works if you move the entire loop body into its own function. Then you don't need the inline anonymous function. So this code:
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++) {
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})(marker, data);
}
would become:
// Looping through the places list
for( var i = 0, length = places.length; i < length; i++ ) {
addPlace( places[i] );
}
// Add one place marker
function addPlace( place ) {
var latLng = new google.maps.LatLng( place.lat, place.lng );
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: place.title
});
// Attaching a click event to the current marker
google.maps.event.addListener( marker, "click", function(e) {
infoWindow.setContent( place.description );
infoWindow.open( map, marker );
});
}
It does the same thing, just a little simpler this way.
One other thought: The styled map stuff is very cool—I'm a big fan of styled maps myself—but I wonder if it should be left out here for the sake of simplicity, since it isn't related to the OP's question?
Feel free to incorporate any of these ideas into your own answer if you like them, and if anyone else finds this variation useful, please upvote Joan's answer since that's where the original code came from.

Categories

Resources