how to show user location on Google maps using "onclick" function? - javascript

I'm trying to build a website that shows a map and on top of it I want to display a button that takes you to your current location.
I'm using Google maps service to pull out the map, I also manage to get the user location by itself so all the JavaScript seems to be working fine but when add the function getlocation to the code and try to call it from the HTML it doesn't work. I believe that is probably not finding the function and I can't figure out why?
I will leave the code below:
<script>
var map;
function initialize() {
var miami = new google.maps.LatLng(41.85, -87.65);
var mapOptions = {
zoom: 4,
center: miami,
disableDefaultUI: true,
}
map = new google.maps.Map(document.getElementById('mymap'),
mapOptions);
var myloc = document.getElementById("try");
function getlocation () {
//code
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
}
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I'm using inline style for everything. I'm somehow new into this of JavaScript so if could please tell me where is my error or what else do I need to make a button from the HTML call a function on JavaScript.
In addition here is the HTML button and map div
<style>
html, body, #mymap{
height: 100%;
margin: 0px;
padding: 0px
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true"></script>
<body>
<div id="try"><button onclick="getlocation()">Click here</button></div>
<div id="mymap"></div>
</body>
If you don't understand what my question is please also comment!
This is my first question here!

google.maps.event.addListener(map, 'click', function(event) {
marker = new google.maps.Marker({position: event.latLng, map: map});
});

Related

My google places kml url javascript

i have a problem with my places from google maps, i already have a functionality map with a file kml in my https server, but i don't want to download and upload the map every time I make changes, not work for me only embed I need manipulated with API, so this is my code:
var map;
var src = 'MY_SERVER/points_vl.kmz';
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
center: new google.maps.LatLng(20.63736, -105.22883),
zoom: 2,
});
loadKmlLayer(src, map);
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
var circle = 'http://www.nearby.org.uk/google/circle.kml.php?radius=5miles&lat='+position.coords.latitude+'&long='+position.coords.longitude;
loadKmlLayer(circle, map);
map.setCenter(pos);
setTimeout(function(){
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Current Location'
});
infowindow.setPosition(pos);
}, 2000);
});
}
}
function loadKmlLayer(src, map) {
var kmlLayer = new google.maps.KmlLayer(src, {
suppressInfoWindows: true,
preserveViewport: false,
map: map
});
google.maps.event.addListener(kmlLayer, 'click', function(event) {
var content = event.featureData.infoWindowHtml;
var testimonial = document.getElementById('capture');
testimonial.innerHTML = content;
});
}
This work fine, but have a way for direct the kml from my url of google maps places?
Using an existant Google 'My Places' map with Maps API v3 styling this thread have some idea, but not work, if you get a idea how make it will make it wonderful
Go to your "MyMap" map. Click on the three dots next to the name of the map, click on "Export to KML":
Choose the "Keep data up to date with network link KML (only usable online):
Rename the .kmz file to .zip, then open it and open the doc.kml file it contains. That file will have the direct link to the KML data specifying your "MyMap".
Use that link in a google.maps.KmlLayer
proof of concept fiddle
original MyMap
code snippet:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 11,
center: {
lat: 41.876,
lng: -87.624
}
});
var ctaLayer = new google.maps.KmlLayer({
url: 'https://www.google.com/maps/d/kml?mid=1-mpfnFjp1e5JJ1YkSBjE6ZX_d9w',
map: map
});
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
<div id="map"></div>
<!-- add your own API key. -->
<script async defer src="https://maps.googleapis.com/maps/api/js?callback=initMap&key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk">
</script>

Google Maps: Marker will not show up?

"use strict"; // eslint-disable-line
var map;
var initialLocation;
// TODO: Initialize and display Google Map
function initialize() {
//get current location
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,position.coords.longitude);
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
}
var mapProp = {
center:initialLocation,
zoom:6,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("googleMap"),mapProp);
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
I am trying to set a marker to my current location using Javascript. When I load the map, however, while the map will center on my current location, no marker will appear?
Everything looks good, just add marker.setPosition(initialLocation); in the following section:
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
marker.setPosition(initialLocation);// ****** missing line ******
map.setCenter(initialLocation);
}, function() {
handleNoGeolocation(browserSupportFlag);
});
};
Here is a working JSFiddle with the necessary changes.
The key is from a Google MAP API sample and will need to be updated with your own, which you can obtain here: Google MAP API.
You may need to reload the JSFiddle example, as there appears to be an issue with the async defer coming from googleapis file. Wait a few seconds and press RUN.
Just make sure the content of variable initialLocation.
If it has the correct lon/lat, marker will appear.
You have to make sure it has correct value before the following:
var marker = new google.maps.Marker({
position: initialLocation,
map: map
});

Google maps api v3 not loading in maps

I have a problem with google maps, I have tried to just to set up a normal map, but nothing works all I get is this image:
And this is my code for this:
(function ($) {
var marker;
var map;
var iconBase = 'https://maps.google.com/mapfiles/ms/icons/';
var infowindow;
function initialize() {
getCoordinate(function (location) {
setUpMap(location.latitude, location.longitude);
});
}
function setUpMap(lat, long)
{
var myLatlng = new google.maps.LatLng(lat, long);
var mapOptions = {
zoom: 8,
center: myLatlng,
mapTypeControl: false,
streetViewControl: false,
mapTypeId:google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
codeAddress();
}
function codeAddress()
{
//Resellers is a global varaible that holds all the resellers addresses
Object.keys(resellers).forEach(function(key){
var reseller = resellers[key];
marker = new google.maps.Marker({
map: map,
position: new google.maps.LatLng(reseller.lat, reseller.lng),
icon: iconBase + 'green-dot.png'
});
(function (marker) {
// add click event
google.maps.event.addListener(marker, 'click', function () {
if (infowindow) {
infowindow.close();
}
infowindow = new google.maps.InfoWindow({
title: key,
content: '<div style="color: black; height: 150px;">' + reseller.address + '</div>'
});
infowindow.open(map, marker);
});
})(marker);
gmaerksp.push(marker);
});
}
function getCoordinate(callback) {
navigator.geolocation.getCurrentPosition(
function (position) {
var returnValue = {
latitude: position.coords.latitude,
longitude: position.coords.longitude
};
var location = returnValue;
callback(location);
}
);
}
google.maps.event.addDomListener(window, 'load', initialize);
}(jQuery));
#map-canvas{
width: 1200px;
height: 600px;
}
<script src="https://maps.googleapis.com/maps/api/js"></script>
And I have no idea why the map is not loading, the markers is loading as it should. But as you can see, the zoom tools is not correctly loading either. So you guys have any idea what is wrong? I have tested with change the div size to but it still loads the same.
Well after more debugging, I found the answer! It seems like google maps can't be inserted with wordpress shortcode. I don't know why, but as soon as I move it out to it is own template instead it works like a charm.
So if any other persons have the same problem out there, and have put there google maps in a shortcode, try to move it out from there and see if it works.

Geolocation service failed on Mobile with google maps api

I am using the following script on my site:
<script type="text/javascript">
var map;
function initialize() {
var mapOptions = {
zoom: 10,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map_canvas'),
mapOptions);
var kmlLayer = new google.maps.KmlLayer("https://maps.google.ca/maps/ms?ie=UTF8&msa=0&output=kml&msid=210000746142049190989.0004ce14b7a8e95167602");
kmlLayer.setMap(map);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'Location found using HTML5.'
});
map.setZoom(14);
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: errorFlag
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I am also using the following which is needed for mobile
<script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?sensor=true"></script>
But still when I visit the site on mobile, and I click to view the map I get the error "The Geolocation service failed."
Is there somthing else I am missing for the geo-location to work on mobile?
You can see the site and live example here on the site, right hand side if you scroll down just past the fold you will see "where can I get rumble?" click on that for the map.
EDIT I think it has somthing to do with the kmlLayer it seems to be defaulting to that on mobile?
var kmlLayer = new google.maps.KmlLayer("https://maps.google.ca/maps/ms?ie=UTF8&msa=0&output=kml&msid=210000746142049190989.0004ce14b7a8e95167602");
kmlLayer.setMap(map);
According to Google Maps zoom gets overridden, when using a kml file
in the function initialize, replace all you have before // Try HTML5 geolocation with:
var mapOptions = {
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions);
var kmlLayer = new google.maps.KmlLayer("https://maps.google.ca/maps/ms?ie=UTF8&msa=0&output=kml&msid=210000746142049190989.0004ce14b7a8e95167602", { map: map, preserveViewport: true });

Add a share button in google map comment

I have a Jscript which using HTML5 geoloaction,
It works perfectly. i want to add a share button where it shows my position, But i cant find how i can add a button here
<script src="https://maps.googleapis.com/maps/api/js?secretapi&sensor=true"></script>
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 18,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
// Try HTML5 geolocation
if(navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
var pos = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
var infowindow = new google.maps.InfoWindow({
map: map,
position: pos,
content: 'your pos' +pos //**i want add a fb share button here**
});
map.setCenter(pos);
}, function() {
handleNoGeolocation(true);
});
} else {
// Browser doesn't support Geolocation
handleNoGeolocation(false);
}
}
function handleNoGeolocation(errorFlag) {
if (errorFlag) {
var content = 'Error: The Geolocation service failed.';
} else {
var content = 'Error: Your browser doesn\'t support geolocation.';
}
var options = {
map: map,
position: new google.maps.LatLng(60, 105),
content: content
};
var infowindow = new google.maps.InfoWindow(options);
map.setCenter(options.position);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
Infowindow can have html markup as content. So if you want to add a button you can simply
do
content: 'your pos' + pos + '<button></button>'
Consider it as a div that can take any html markup, which can be styled too (the markup, not the window).
A demo
UPDATE
For binding an event on a dynamic element (in your case the button) you could do the following
content: 'your pos' + pos + '<button id="myButton"></button>'
And in your js script do the following
$("body").on("click", "#myButton", function(e) {
// ...
});
Mind the fact that the above is a method of the jQuery object so be sure to include the jquery library.
A new demo press the button and see the alert that is being called in the binding

Categories

Resources