Leafletjs show my location marker instead of hardcoded location - javascript

I am trying out Leaflet.js and I have a map with a marker like this:
var marker = new L.marker([5.897818, -1.120009],{
draggable: true,
autoPan: true
}).addTo(mymap);
This is showing ok but I want it to appear on my current location instead of the above hardcoded location.
How do I do this?

What you need is to tap into the Geolocation API and use the results of that to create a marker.
var mymap = L.map('mapid').setView([51.505, -0.09], 13);
navigator.geolocation.getCurrentPosition(position => {
const { coords: { latitude, longitude }} = position;
var marker = new L.marker([latitude, longitude], {
draggable: true,
autoPan: true
}).addTo(mymap);
console.log(marker);
})
There's some issue issue using the API with Stackoverflow, so here's a link to a working JSFiddle.

Related

My custom marker on my google map wont show

I want to use an image(.jpg) that I have as a marker instead of the default marker/pin on my Google map. But the image won't show. There are lots of the same questions on this forum but none of them has helped me.
As soon as I take away the icon attribute from google.maps.Marker object the default marker shows. So that indicates that it somehow can't find my image... right?
Even when I hardcode the following link
https://maps.gstatic.com/mapfiles/place_api/icons/geocode-71.png
that marker image shows. But not the one I have locally in my project.
var map = null;
var mapHub;
var markers = [];
$(function ()
{
mapHub = $.connection.myHub;
//Start the hub
$.connection.hub.start(function ()
{
//Get the current location from the browser
navigator.geolocation.getCurrentPosition(function (position)
{
//Create the map element on the page.
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: position.coords.latitude, lng: position.coords.longitude },
zoom: 15
});
//Add marker of current position to map
markers.push(new google.maps.Marker({
position: { lat: position.coords.latitude, lng: position.coords.longitude},
map: map,
icon: '~/Images/MapMarkerIcon.jpg'
}));
});
});
});

adding URL to map marker in Marker Cluster google map API

So basically what I am trying to do is have a map cluster and once you click into the clusters and click on the individule map markers you will be linked off to a different page on my website.
this is what i have so far. but i cant seem to pull the URLS through.. into different markers.
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -39.3642, lng: 164.0444318}
});
// 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,
url: "http://travelpark.co.nz" //Will be different for each marker
});
});
// 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: -37.7862985, lng: 175.2773836},
{lat: -37.8011434, lng: 174.871265}
]
google.maps.event.addListener(markers, 'click', function() {
window.location.href = this.url;
});
The event listener at the bottom doesnt work.. i cant seem to figure this out. any help would be appreciated
Assign listener to each marker object not to the array. Use your map function itself to avoid 2 for loops:
var markers = locations.map(function(location, i) {
var marker = new google.maps.Marker({
position: location,
url: "http://travelpark.co.nz" //Will be different for each marker
});
google.maps.event.addListener(marker, 'click', function(){
window.location.href = this.url;
});
return marker;
});

Display Marker on Custom Google Map

I am using JQuery mobile, HTML5 to develop a real time vehicle tracking application. I would like to know how to place a marker at the current location on a 'custom' map. I am using the getLocation function to get the current coordinates.
var mapOptions={
zoom:15
mapTypeControl: true;
navigationControlOptions:{style:google.maps.navigationControl.Style.Small}mapTypeID.ROADMAP};
map=google.maps.Map(document.getElementByID("map_container"),mapOptions);
var marker = new google.maps.Marker({
position: coords,
map: map,
title: "You Are Here!"
});
}
the google.maps.Map function loads a 'new' map. I would like to display the marker on a custom map.
you need to load the coords into a LatLng object before passing it to the marker.
eg
var myLatlng = new google.maps.LatLng(coords[0], coords[1]);
here coords[0] and coords[1] are float type latitudes and longitudes values.
after this pass the variable myLatlng inplace of coords in the marker.
This is some code i used in a project:
function CurrentPosition(){
getPosition(function(mylat, mylng){
drawPosition(mylat, mylng);
});
}
function getPosition(callback) {
navigator.geolocation.getCurrentPosition(function(position){
callback(position.coords.latitude, position.coords.longitude);
}, function(){
alert(texte['myPositionErrorAlert']);
},{enableHighAccuracy: false, timeout: 20000, maximumAge: 0});
}
function drawPosition(mylat, mylng){
LatLng = new google.maps.LatLng(mylat, mylng);
yourMarker = new google.maps.Marker({
position: LatLng,
map: map,
title:"MyPosition"
});
yourMarker.setMap(map);
}
Force the CurrentPosition funcition, the getPosition() will locate your position and the drawPosition() will create the marker.

Maps API v3: New InfoWindow, with pixelOffset, w/ data from KML.

Hello: I'm making progress on my Google Map (see my previous post: KML markers missing on Google Maps API v3: What's wrong?), but I'm now stuck, and hoping for help.
My custom-styled map pulls from a KML file with about 20 Placemarks.
For design reasons, I want my Placemarks to open on the RIGHT side of the anchor, rather than the default top/center. I've tried searching in vain for a simple way to do this; closest I've come is: Issue with infowindows remaining active when another KML layer is selected - Google Maps API V3, which I can't make work for me.
Here is an example of what I'm looking for: http://nationaltreasures.aircanada.com/ (its InfoWindows open to right).
I think I need to supress the default InfoWindow, create my own that pulls the KML data, and then specify a pixelOffset to my custom InfoWindow, but I can't figure out how to do it.
Thank you in advance!
function initialize() {
var styles = [ ]; // Styles removed to simplify code
var styledMap = new google.maps.StyledMapType(styles,
{name: "HEPAC"});
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(46.69504, -67.69751),
panControl: false,
mapTypeControl: false,
streetViewControl: false,
noClear: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
mapTypeControlOptions: {
mapTypeIds: ['map_style', google.maps.MapTypeId.ROADMAP]
}
};
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var opt = { minZoom: 7, maxZoom: 9 }; // Sets minimum & maximum zoom level
map.setOptions(opt);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://hepac.ca/wp-content/mapping/wellnessnetworksl.kml?f=3',
preserveViewport: true,
});
ctaLayer.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
Thanks to #SeanKendle for pointing me in the right direction. Found more or less what I wanted by adding this into my original code.
google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
showInContentWindow(kmlEvent.latLng, kmlEvent.featureData.description);
});
function showInContentWindow(position, text) {
var content = "<div>" + text + "</div>";
var infowindow = new google.maps.InfoWindow({
content: content,
position: position,
pixelOffset: new google.maps.Size(300, 0),
})
infowindow.open(map);
}
antyrat posted about this with an infoWindow to the right of the marker here:
Googlemap custom infowindow
See the link in the accepted answer.
EDIT: Here's an example. Obviously you will want to include InfoBox.js on your page to get access to that plugin. I hope this works, I didn't test it, but it might point you in the right direction:
function initialize() {
var styles = [ ]; // Styles removed to simplify code
var styledMap = new google.maps.StyledMapType(styles,
{name: "HEPAC"});
var mapOptions = {
zoom: 7,
center: new google.maps.LatLng(46.69504, -67.69751),
panControl: false,
mapTypeControl: false,
streetViewControl: false,
noClear: true,
zoomControlOptions: {
position: google.maps.ControlPosition.TOP_RIGHT
},
mapTypeControlOptions: {
mapTypeIds: ['map_style', google.maps.MapTypeId.ROADMAP]
}
};
google.maps.visualRefresh = true;
var map = new google.maps.Map(document.getElementById("map-canvas"),mapOptions);
map.mapTypes.set('map_style', styledMap);
map.setMapTypeId('map_style');
var opt = { minZoom: 7, maxZoom: 9 }; // Sets minimum & maximum zoom level
map.setOptions(opt);
var ctaLayer = new google.maps.KmlLayer({
url: 'http://hepac.ca/wp-content/mapping/wellnessnetworksl.kml?f=3',
preserveViewport: true,
});
ctaLayer.setMap(map);
google.maps.event.addListener(ctaLayer, 'click', function(kmlEvent) {
var text = kmlEvent.featureData.description; // ALTER THIS TO POINT TO THE DATA YOU WANT IN THE INFOBOX
var infoBox = new InfoBox({content: text, latlng: kmlEvent.position, map: map});
});
}
Google Maps API says:
Additionally, a click on a KML feature generates a KmlMouseEvent,
which passes the following information:
position indicates the latitude/longitude coordinates at which to anchor the InfoWindow for this KML feature. This position is generally
the clicked location for polygons, polylines, and GroundOverlays, but
the true origin for markers.
pixelOffset indicates the offset from the above position to anchor the InfoWindow "tail." For polygonal objects, this offset is typically
0,0 but for markers includes the height of the marker.
featureData contains a JSON structure of KmlFeatureData.
See this page for more info: KML Feature Details

Changing Google Maps V3 Maker Icon the correct way?

The code in example 1 works. I would like to understand the marker.setIcon(); function more (new to JavaScript also).
My question is. In the documentation for Google maps you see something like this for changing the marker.
MarkerImage(url:string, size?:Size, origin?:Point, anchor?:Point, scaledSize?:Size)
How does this relate to what I have done in example 1 for setting up marker Icon, shoud I have done somethign like this instead?
marker = google.maps.MarkerImage({
url: "newIcon.png"
});
marker.setIcon(marker);
and would that have worked?
here is my example
Example 1
function initialize(){
//MAP
var latlng = new google.maps.LatLng('xxx','xxx');
var options = {
zoom: 16,
center: latlng,
mapTypeId: google.maps.MapTypeId.SATELLITE
};
map = new google.maps.Map(document.getElementById("map_canvas"), options);
//GEOCODER
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: true
});
marker.setPosition(latlng);
marker.setIcon("newIcon.png");
map.setCenter(latlng);
}
You're giving a V2 answer for a V3 question.
There is no GIcon in V3.
var image = new google.maps.MarkerImage("newIcon.png");
Can be used inside your marker as the icon.
var marker = new google.maps.Marker({
position: new google.maps.LatLng(lat,lng),
icon:image
});

Categories

Resources