"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
});
Related
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>
I am learning to use javascript right now with Rails and I'm having some issues with updating my markers according to my current position using AJAX. I believe the ready page:load is not running the updated coords that have been attached as a data-attribute, coords since the page is not technically reloading. How can I use my current position data and update it with events with longitude/latitude values?
var map;
$(document).on('ready page:load', function() {
if ("geolocation" in navigator) {
myMap.init();
var coords = $('#map-canvas').data('coords');
if (coords){
myMap.addMarkers(coords);
}
}
});
myMap.init = function() {
if(navigator.geolocation){
var mapOptions = {
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
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
});
var marker = new google.maps.Marker({
position: new google.maps.LatLng(position.coords.latitude, position.coords.longitude),
map: map
});
map.setCenter(pos);
var latitude = position.coords.latitude;
var longitude = position.coords.longitude;
$.ajax({
url:"/all_events",
method: "GET",
data: {
latitude: latitude,
longitude: longitude
},
dataType: 'script'
});
});
} else {
document.getElementById('map-canvas').innerHTML = 'No Geolocation Support.';
}
};
myMap.addMarkers = function(coords){
var image = "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png"
coords.forEach(function(coord){
var myMarker = new google.maps.Marker({
position: new google.maps.LatLng(coord.latitude, coord.longitude),
map: map,
icon: image
});
});
}
In order to make your script work in the way you want please try out the following steps:
Put your foreach loop in a function and call it at the end of your successive AJAX callbacks.
Load the AJAX once the Google Maps have finished loading completely. If Google Maps library has not finished loading than you wont be able to create a Google LatLng object, this is what is probably happening over here.
Hope this would help
I'm dynamically loading latitude/longitude variables and passing them to the Google Maps Initialize(); function.
function initialize() {
var lat = $('.map_img', '.inview').attr('data-lat');
var lng = $('.map_img', '.inview').attr('data-lng');
var myLatlng = new google.maps.LatLng(lat, lng);
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var marker = new google.maps.Marker({
position: myLatlng,
map: map
});
google.maps.event.trigger(map, 'resize');
}
So I'm pulling these coordinates via the data attribute, which is set via a wordpress widget and giving them to Google Maps.
I want to run the function, getting new coordinates every time the user clicks these left/right buttons.
previous
next
$('.btn-prev').click(function () {
//initialize maps script again
initialize();
});
$('.btn-next').click(function () {
//initialize maps script again
initialize();
});
Then the user clicks on a Map image which opens the large map with the new coordinates.
var mapImg = $('.map_img');
var $overlay = $('.overlay'),
resize = true,
map;
mapImg.click(function () {
$overlay.show();
if (resize) {
initialize();
resize = false;
}
});
The problem I'm having is that after the first click the Map is not centered. I had assumed google.maps.event.trigger(map, 'resize'); would solve this problem.
I'm not sure why this is happening so I've created a fiddle to replicate the issue.
http://jsfiddle.net/SEOplay/3CXSs/13/
Help much appreciated.
Try using:
google.maps.event.addDomListener(window, "click", function () {
var center = map.getCenter();
google.maps.event.trigger(map, "resize");
map.setCenter(center);
});
Not efficient code because I'm not excatly sure how it fits into your code, but it will recenter the map every time someone clicks somewhere. It should give you some idea of the code you need, if you have any trouble let me know.
JSFiddle (you also seem to have a bug where it doesn't change the map on the first next/prev click.
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 });
I have a somewhat strange problem. I have two maps on my site, a big one and a small one. I want to use the big one to show a route to a certain address. I'm now trying to implement the two maps but get a weird problem. The small map is working fine, but on the big map only a small area of the div is filled with the map, the rest is empty. (See the image.)
I use the following code to display the two maps:
function initialize() {
var latlng = new google.maps.LatLng(51.92475, 4.38206);
var myOptions = {zoom: 10, center: latlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({position: latlng, map:map, title:"Home"});
var image = '/Core/Images/Icons/citysquare.png';
var myLatLng = new google.maps.LatLng(51.92308, 4.47058);
var cityCentre = new google.maps.Marker({position:myLatLng, map:map, icon:image, title:"Centre"});
marker.setMap(map);
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
jQuery(document).ready(function () {
[..]
initialize();
});
What's going wrong here?
EDIT:
Unfortunately the suggestions below doesn't seem to work. The closes i came is to remove the display:none from the elements and set the elements to hide with jquery
[..]
jQuery(document).ready(function () {
[..]
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).hide();
});
With the following result
Yes, #Argiropoulos-Stavros but, Add it as a listener
google.maps.event.addListenerOnce(map, 'idle', function(){
google.maps.event.trigger(map, 'resize');
map.setCenter(location);
});
It will begin re-sizing after, map rendered.
I think you are using v3.
So google.maps.event.trigger(map, "resize");
Also take a look at here
I fixed it!
I made an own function for the largemap and placed it in the callback when the elements are opened
function largeMap(){
var largeLatlng = new google.maps.LatLng(51.92475, 4.38206);
var largeOptions = {zoom: 10, center: largeLatlng,mapTypeId: google.maps.MapTypeId.ROADMAP};
var largeMap = new google.maps.Map(document.getElementById("largeMap"), largeOptions);
var largeMarker = new google.maps.Marker({position: largeLatlng, map:largeMap, title:"Cherrytrees"});
largeMarker.setMap(largeMap);
}
[..]
$("#showRoute").click(function(e){
e.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeIn(500);
$("#shadowContent").show().css({'width':'750px','top':'25px','left':'50%','margin-left':'-400px'});
$("#closeBarLink").click(function(l){
l.preventDefault();
$("#shadow").add($("#shadowContent"),$("#closebar"),$("#content")).fadeOut(500);
});
largeMap();
});
Thanks anyway!!
call initialize(); function after you box active.
$(document).ready(function () {
$("#shadow").show(function () {
initialize();
})
});
When you're loading in the large map, try adding this at the end of your map code.
map.checkResize();
When Google Maps first renders on your page, it has the dimensions recorded so that it displays the map images in that size. If you're resizing the map dynamically, you need to tell the API to check the new size.
<script type='text/javascript' >
var geocoder, map;
function codeAddress() {
var address= '<?php echo $this->subject()->address; ?>';
geocoder = new google.maps.Geocoder();
geocoder.geocode({
'address': address
}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var myOptions = {
zoom: 13,
center: results[0].geometry.location,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location,
icon:'http://rvillage.com/application/themes/rvillage/images/map-marker.png'
});
var infowindow = new google.maps.InfoWindow({ content: 'coming soon' });
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map, this);
});
}
});
}
jQuery(document).ready(function () {
codeAddress();
});
</script>
You are using pop up window with jQuery, and I guest you call initialize() function when document is ready ( $(document).ready(function() {initialize(); }) ).
Try call initialize() function after pop up windown showed.
Johnny