Add multiple markers in google maps - javascript

I am adding google maps to my website and I am able to get my current location but now I want to add markers to differnet places on map.How I can do that?My code to get current location is as:
<div id="map"></div>
<script>
function initMap() {
var myLatlng = {lat: 40.59726025535419, lng: 80.02503488467874};
var map = new google.maps.Map(document.getElementById('map'),{
center:myLatlng,
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Your Location.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBn7svjyYLYuP-EzakUjobLmpPi41l1_hw&callback=initMap">
</script>

after you create new google.maps.Map (in your case, variable map)
var marker = new google.maps.Marker({
position: {lat: 40.59726025535419, lng: 80.02503488467874},
map: map,
title: 'Hello World!'
});
var marker2 = new google.maps.Marker({
position: {lat: 40.59726025535419, lng: 80.02503488467874},
map: map,
title: 'Hello World!'
});
Source: https://developers.google.com/maps/documentation/javascript/examples/marker-simple#try-it-yourself
Demo - updated.
https://jsbin.com/bazoco/edit?html,console,output
Try this function buddy - updates v3
function appendMarker(map, latitude, longitude, text) {
var pos = {lat: latitude, lng: longitude};
var markerOption = {
position: pos,
map: map,
title: text || 'Hello World!'
};
return new google.maps.Marker(markerOption);
}
//Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Your Location.');
map.setCenter(pos);
//could you add this code below and test ?
var markerOp = appendMarker(map, position.coords.latitude, position.coords.longitude, 'Hello');
var markerOp2 = appendMarker(map, position.coords.latitude + 0.005, position.coords.longitude + 0.005, 'Hello');
//could you add this code above and test ?
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});

you can create marker object and pass latlng object to it
first make google map LatLng Object
var latlng = new google.maps.LatLng(latitude, longitude);
then use this latlng object as position in marker object
var marker = new google.maps.Marker({position: latlng,map: map,})
marker.setMap(map);

var myLatlng = {lat: 40.59726025535419, lng: 80.02503488467874};
var marker = new google.maps.Marker({
position: myLatLng,
map: map,
title: 'Your LatLng!'
});
var marker2 = new google.maps.Marker({
position: {lat: 40.60, lng: 80.1},
map: map,
title: 'Your second marker!'
});
var marker3 = new google.maps.Marker({
position: {lat: 40.62, lng: 80.5},
map: map,
title: 'Your third marker!'
});
Next time read the documentation first :-)
Working fiddle: https://jsfiddle.net/kLndyr00/1/

Related

How to change Google Maps info window to a geolocation marker

I followed a tutorial by Google https://developers.google.com/maps/documentation/javascript/geolocation so I could display the users position on a map. It currently looks like this with an info window:
However I would like to display a geolocation marker instead of the info window:
Here is my code:
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(52.520008, 13.404954)
};
infoWindow = new google.maps.InfoWindow;
map = new google.maps.Map(document.getElementById("map"), mapOptions);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
Any help on how to change it from an info window to geolocation marker would be great. Thanks in advance.
To display location with marker in Google maps, you can try this:
var map = new google.maps.Map(document.getElementById("map"), {
center: {lat: 52.520008, lng: 13.404954},
zoom: 8,
mapTypeId: 'roadmap'
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(52.520008, 13.404954),
map: map,
/*if you want to custom marker icon, you can set icon path here*/
icon: 'your_icon_url',
/* if you don't want to enable dragging, just remove this property */
draggable: true
});
// if you enable dragging, you can initialize this event
// to get latitude, longitude and address
google.maps.event.addListener(marker, 'dragend', function (marker) {
var latLng = marker.latLng;
var currentLatitude = latLng.lat();
var currentLongitude = latLng.lng();
var geocoder = new google.maps.Geocoder;
var latlng = { lat: currentLatitude, lng: currentLongitude };
geocoder.geocode({ 'location': latlng }, function (results, status) {
if (status === 'OK') {
// address
console.log(results);
} else {
console.log('Geocoder failed due to: ' + status);
}
});
});
Note: To work with places in Google maps, you need to require libraries=places as a parameter inside the url:
https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places
Reference: For more marker icons designed by Google, you can refer here: What are the filenames of new colored Google maps markers?

Google Map APIs - Combining geolocation and cluster markers

I am creating a website for ad classifies. I would like the users to see where the location of the item is on a map near their location.
Using Google's JS code templates for Geolocation and Cluster Markers work separately, when added to the same JS, they don't work. Is there a way to combine the JS for them to work on the same map?
Thanks in advance
Edit - I have added the JS codes
/* Geolocation */
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
/* Map Clustering */
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 6,
center: {lat: 55.378052, lng: -3.435973}
});
var labels = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
var markers = locations.map(function(location, i) {
return new google.maps.Marker({
position: location,
label: labels[i % labels.length]
});
});
var markerCluster = new MarkerClusterer(map, markers,
{imagePath: 'https://developers.google.com/maps/documentation/javascript/examples/markerclusterer/m'});
}
var locations = [
{lat: 55.633792, lng: -4.661550},
{lat: 55.864239, lng: -4.251806},
{lat: 55.614302, lng: -4.665554},
{lat: 55.543781, lng: -4.664010},
{lat: 55.551993, lng: -4.623667},
{lat: -26.246920, lng: -4.523914}
]
It is a bit difficult to answer your question without any specific samples. you will need to combine the geolocation JS code onto the cluster markers, which is an obvious answer. So if you have a sample of your code, we will be able to help.

Can't add a marker in this code anyhow

I have tried to use traditional marker function with this code but the marker is not visible. How can I add marker attached to this info window.
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 22.5726,
lng: 88.3639
},
zoom: 13
});
infoWindow = new google.maps.InfoWindow;
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent("You're here Bro!");
infoWindow.open(map);
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
new AutocompleteDirectionsHandler(map);
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
infoWindow.open(map);
}
Your code is missing the marker component
Use the below code.
var marker = new google.maps.Marker({
position: {lat: 22.5726, lng: 88.3639},,
map: map,
title: 'Text to show on mouseover on this marker'
});

Google MyMaps Geolocation // GPS

I created a Map in MyMaps an implemented it to an php document.
It works good. But i would like so set the Geolocation when it starts.
Is that possible?
The following script Show me a Google Map with the Geolocation. How can I implement here My Map?
Thanks for helping!
<script>
function initialize(coords)
{
var latlng = new google.maps.LatLng(coords.latitude, coords.longitude);
var myOptions =
{
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("pos"), myOptions);
var marker = new google.maps.Marker(
{
position: latlng,
map: map,
title: "Hier bist du :)"
});
}
navigator.geolocation.getCurrentPosition(function(position)
{
initialize(position.coords);
}, function()
{
document.getElementById('pos').innerHTML = 'Deine Position konnte leider nicht ermittelt werden';
});
</script>
This is the code you should implement:
<script >
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 6
});
var infoWindow = new google.maps.InfoWindow({map: map});
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
</script>
SOURCE
Add the embedded Map iframe into your HTML.
Check My Maps Documentation for more info.
<iframe id="map-iframe" src="https://www.google.com/maps/d/u/2/embed?mid=YOUR_MAP_ID" width="640" height="480"></iframe>
Use Geolocation in your JavaScript file to get user's current location.
And set the map to show user's location by adding &ll=lat,long at the end of your map's URL.
// getting user's current location.
navigator.geolocation.getCurrentPosition(
(position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
console.log(pos);
// setting the map to show user's current location.
document.getElementById('map-iframe').src = mapUrl.concat('&z=16&ll=', position.coords.latitude, ',', position.coords.longitude);
console.log(document.getElementById('map-iframe').src);
});
} else {
alert('Error: Your browser doesn't support geolocation.');
}
}

Combine Geolocation and markers using Google Maps Javascript

I'm trying to create a map that shows your current locations and show markers in the city. So you can see if you are nearby a marker.
I have to codes at this time, and I need to combine them. But when i do that, the codes doesn't work anymore. Does somebody know how to combine those two JS? If not, is there a other way to do this?
This is the JS for Geolocation:
function initMap()
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
zoom: 14,
});
var infoWindow = new google.maps.InfoWindow({map: map});
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
map.setCenter(pos);
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
And this is the JS code I have made for the markers:
google.maps.event.addDomListener(window, 'load', initialize);
var map;
var currentPage = 'mapA';
var markers = [
['Thuis',52.2203713,6.90032999999994],
['Bommelstein',52.22254299999999,6.911623800000029],
['Saxion', 52.21976009999999,6.889364500000056],
['Kroeg', 52.2206085,6.896547300000066],
['t Gat', 52.2211657,6.895848999999998],
['studieruimte de Bul', 52.22101940903001,6.8924690438436755]
];
function initialize() {
var mapOptions = {
zoom: 14,
disableDoubleClickZoom: true,
draggable: true,
panControl: false,
scrollwheel: true,
zoomControl: true,
streetViewControl: false,
overviewMapControl: false,
mapTypeControl: false,
center: new google.maps.LatLng(51.489031, 7.039671)
};
map = new google.maps.Map(document.getElementById('map-canvas'),mapOptions);
setMarkers();}function setMarkers(){
for (i = 0; i < markers.length; i++) {
var post = new google.maps.LatLng(markers[i][1], markers[i][2]);
var marker = new google.maps.Marker({
position: post,
map: map
});
var infowindow = new google.maps.InfoWindow({
content: markers[i][0]
});
infowindow.open(map,marker);
}
}
I am actually working on the samething had the same problem until a few minutes ago. I simply start the geolocation condition to find the position before declaring an object of the map and it worked for me. here is my simple code similar to yours:
function initMap() {
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var currentpos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var map = new google.maps.Map(document.getElementById('map'), {
center: currentpos,
zoom: 14,
});
var contentString = 'I found you';
var infowindow = new google.maps.InfoWindow({
content: contentString
});
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'marker with infoWindow'
});
marker.addListener('click', function() {
infowindow.open(map, marker);
});
}, function() {
handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
handleLocationError(false, infoWindow, map.getCenter());
}
}
function handleLocationError(browserHasGeolocation, infoWindow, pos) {
infoWindow.setPosition(pos);
infoWindow.setContent(browserHasGeolocation ?
'Error: The Geolocation service failed.' :
'Error: Your browser doesn\'t support geolocation.');
}
Best of luck

Categories

Resources