I'm struggling through the Google maps API to create multiple markers with a link for each. Being a javascript noob doesn't help either.
This is my code so far:
<div id="map"></div>
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: {lat: -27.469703, lng: 153.025190}
});
// Create an array of alphabetical characters used to label the markers.
var labels = 'X';
// Add some markers to the map.
// Note: The code uses the JavaScript Array.prototype.map() method to
// create an array of markers based on a given "locations" array.
// The map() method here has nothing to do with the Google Maps API.
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
// Add a marker clusterer to manage the markers.
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: -27.449916, lng: 153.044031},
{lat: -27.476536, lng: 153.020148},
]
</script>
<script src="https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/markerclusterer.js">
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=APIKEYHERE&callback=initMap">
The map displays fine and the markers are there, but everything I've tried to implement the links has been a fail.
Thanks in advance!
You need to add click listeners to each marker. See below:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
marker.linkUrl = 'https://google.com';
marker.addListener('click', function () {
window.location = this.linkUrl;
});
return marker;
});
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 need to place a Google Map made using Javascript API within an iFrame so that I can perform operations on the map and then submit a form that I create below that takes values from the map, for example, the latitude and longitude. How can I make that happen?
<script>
var map;
var circle=null;
myLatlng = {lat: 28.713956, lng: 77.006653};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: myLatlng,
zoom: 13
});
var marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'Click to zoom'
});
google.maps.event.addListener(map, 'click', function (event) {
document.getElementById("lat").value = event.latLng.lat();
document.getElementById("long").value = event.latLng.lng();
marker.setPosition(event.latLng);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=<my-API-key>&callback=initMap"></script>
Also, I need to process the data coming from the map, so I don't want to use Google Maps Embed API. I know it can be placed in an iFrame using it. I have tried doing that but that is not what I need.
I am testing Google Maps API and the code who's coming from the doc not working for me, as the marker is not displayed while I have no problem with the map.
function initMap() {
var place = {lat: 48.1389729, lng: -1.935302};
var map = new google.maps.Map(document.getElementById('maps'), {
zoom: 10,
center: place
});
var marker = new google.maps.Marker({
position: place,
map: map,
visible:true,
title: "Hi There",
});
}
The function is created before calling the API with the callback.
What I am missing ?
Add in HTML after you script
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initMap">
</script>
I am going to need at least 3 maps on the same page (one below the other, not side by side), each containing multiple markers. Can anyone tell me how to get three versions of this on the same page (after which I can amend the details for each one)? I'm basically feeling my way here, not knowing much about javascript.
Many thanks in advance - Roger
<div id="map" style="height:400px;width:541px;display:block;">
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
function mapIt(){
var latlng = new google.maps.LatLng(24.00, 0.00);
var myOptions = {
zoom: 1,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
}
var map = new google.maps.Map(document.getElementById('map'), myOptions);
setMarkers(map, places);
}
var places = [
['London',51.50, -0.125,"Markers/green.png"],
['Abidjan',5.34, -4.03,"Markers/red2.png"],
['Abu Dhabi',24.47, 54.37,"Markers/red2.png"],
];
var popUps = [
'<strong>London</strong><br />link to larger map',
'<strong>Abidjan, Ivory Coast</strong><br />Content here',
'<strong>Abu Dhabi, United Arab Emirates</strong><br />Content here>',
]
var infowindow;
function setMarkers(map, locations) {
for (var i = 0; i < places.length; i++) {
var myLatLng = new google.maps.LatLng(locations[i][1], locations[i][2]);
var icon = locations[i][3];
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: locations[i][0],
icon: icon
});
(function(i, marker) {
google.maps.event.addListener(marker,'click',function() {
if (!infowindow) {
infowindow = new google.maps.InfoWindow();
}
infowindow.setContent(popUps[i]);
infowindow.open(map, marker);
});
})(i, marker);
}
};
mapIt();
</script></div>
I few minutes ago created code which shows how to set four maps in the same page.
See it from JS Fiddle
It basically just boils down to setting correct number of div elements for maps:
<div id="map0"></div>
<div id="map1"></div>
<div id="map2"></div>
<div id="map3"></div>
and initializing them:
var map0 = new google.maps.Map(document.getElementById("map0"), mapOptions);
var map1 = new google.maps.Map(document.getElementById("map1"), mapOptions);
var map2 = new google.maps.Map(document.getElementById("map2"), mapOptions);
var map3 = new google.maps.Map(document.getElementById("map3"), mapOptions);
Edit:
I updated example to add markers to following kind of object so they are easier to be accessed based on what map markers you want to handle.
var markers = {
'map0' : [],
'map1' : [],
'map2' : [],
'map3' : [],
};
It should print following debug information to javascript console:
Marker is: (60.12816100000001, 18.643501000000015) map name is: map0
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (61.92410999999999, 25.748151000000007) map name is: map1
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (32.7151137, -117.15665719999998) map name is: map2
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
Marker is: (35.86166, 104.19539699999996) map name is: map3
(markers['map0'][0]: (60.12816100000001, 18.643501000000015)
So in the example I provided I only add one marker per map, but add as many as you like since markers object has array for each map type.
Cheers.
I need to place multiple markers on a google map. Here's the problem: I have an array of latitude/longitude data. I need to make a marker appear on the map for each lat/lng pair. But it won't. If I ask the function to print out the coordinates instead of marking them on the, map, it works fine. I don't get an error message either way, so I'm stuck. The page displays the map but without any markers. Here's the code of the function that should add markers:
//adds markers to the map
function addMarkers(locarray) {
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locarray.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locarray[i][0], locarray[i][1]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent('some words');
infowindow.open(map, marker);
}
})(marker, i));
}
}
Here's the initialize function (called on body load):
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = codeAddress("<?php echo $_POST['postal']; ?>");
var myOptions = {
zoom: 11,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
}
geocoder and map are declared as global variables. The codeAddress function returns lat and lng of the place I want to center the map around, it's been tested and works perfectly. It is NOT the problem, I'm leaving it out to simplify and keep PHP out of this.
And here is the script that declares the array and calls the addMarkers function:
<script type='text/javascript'>
var locations = [
[-33.890542, 151.274856],
[-33.923036, 151.259052],
[-34.028249, 151.157507]
];
addMarkers(locations)
</script>
Does anyone see anything wrong with this?