My google places kml url javascript - 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>

Related

Multiple google map on modal view Ruby on Rails

I have a list of enterprices and need to display a map on their respective modal, for this I have this:
<div class="row" id="googleMap<%=enterprice.id%>" style="width 100%; height: 300px;" data1='<%=enterprice.latitud%>' data2='<%=enterprice.longitud%>'>
</div>
this code is on a html.erb file.
My function for loading the map:
<script>
function myMap(lat, long) {
var uluru = { lat: lat, lng: long};
var map = new google.maps.Map(document.getElementById('googleMap'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
}
</script>
And a jquery helper for passing the data
$(document).on("ready", function() {
$('#googleMap<%=enterprice.id%>').each(function (index, element) {
var $this = $(element);
myMap($this.attr("data1"), $this.attr("data2"));
});
});
The problem is the map is only loading on the modal for the first cell, but not actually displaying any map.
And the other cells wont even load the map.
First of all, you don't need a map and a modal for each. You can have one and change them using JS. This way you will not overload your page with elements you will only use in series but never together in parallel.
You can have a map defined in your modal whenever the page is ready.
<script>
var map;
var old_marker;
function initMap() {
var point = {lat: 0, lng: 0};
map = new google.maps.Map(document.getElementById('map'), {
zoom: 12,
center: point,
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(point);
}
// Adds a marker to the map and push to the array.
function addMarker(location) {
var marker = new google.maps.Marker({
position: location,
map: map
});
if(old_marker){
old_marker.setMap(null)
}
old_marker = marker
markers.push(marker);
map.setCenter(location);
}
</script>
Now we have to add a marker for each enterprise just by clicking on them.
I suggest adding a certain class to them
$(document).on("ready", function() {
initMap();
$(.enterprise).click(function(){
addMarker($this.attr("data1"), $this.attr("data2"));
});
});
By this, a marker will be added on the click on each enterprise and the map will focus that location. Now all you need to do is show the Modal.
References: https://developers.google.com/maps/documentation/javascript/examples/marker-remove

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.

Google Map with Local Churches, how to construct API call?

Is there are way to retrieve a map from Google using the API so that it displays a list of local churches with churches with markers?
I have the basic syntax, and I have a basic API account setup, but I am not how/if I can use the type field.
var mapOptions = {
center: new google.maps.LatLng("-33.8670522", "151.1957362"),
zoom: 11,
scrollwheel: false,
streetViewControl: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("googlemaps"), mapOptions);
Yes, you can do this, using Google Places API.
I'll use JavaScript API, since you seem to have a map being built with such API.
As said in documentation:
The Places service is a self-contained library, separate from the main Maps API JavaScript code. To use the functionality contained within this library, you must first load it using the libraries parameter in the Maps API bootstrap URL:
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
After this, using JavaScript Places API you can request places by type and a radius (in meters). The maximum allowed radius is 50.000 meters.
Here a piece of code that demonstrate this:
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
var service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
Obs.: In this example, handlePlaceResponse is a callback to handle the response and create the markers. See in the complete example how it works.
This will request by churches in a 5km radius from Sydney point (lat: -33.8670522, lng: 151.1957362).
To overlay markers you'll need handle the response. In the example I used only name to put as content of InfoWindow. You can see details about the response here: Place Details Responses
So, a function to create markers look like this:
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
Also, if you need, for types supported in place search, see this link: Place Type
Here an example using as point the used by you and 5000 meters for radius:
<html>
<head>
<title>Google Maps - Places Sample</title>
<style>
body {
margin: 0;
}
#map {
height: 600px;
width: 100%;
}
</style>
<script src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
<script>
var gm = google.maps;
var map;
var bounds;
var service;
var infowindow;
var sydney = new gm.LatLng(-33.8670522, 151.1957362);
function initialize() {
var options = {
zoom: 15,
center: sydney,
mapTypeId: gm.MapTypeId.ROADMAP,
streetViewControl: false,
scrollwheel: false
};
map = new gm.Map(document.getElementById("map"), options);
var request = {
location: sydney,
radius: 5000,
types: ['church']
};
bounds = new gm.LatLngBounds();
infowindow = new gm.InfoWindow();
service = new gm.places.PlacesService(map);
service.nearbySearch(request, handlePlaceResponse);
}
/**
* Handle place response and call #createMarker to creat marker for every place returned
*/
function handlePlaceResponse(results, status) {
if (status == gm.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
}
/**
* Creates marker with place information from response
*/
function createMarker(place) {
var location = place.geometry.location;
var marker = new gm.Marker({
map: map,
position: location
});
bounds.extend(location);
gm.event.addListener(marker, 'click', function() {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
gm.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="map"></div>
</body>
</html>

Update markers with current position on Google Map API

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

Categories

Resources