I'm having a problem setting a variable in ST_DISTANCE to a variable instead of a number. My goal is to sort fusion table entries by distance to the client and only display the closest 3.
(Also, I would like the window to zoom out and encompass those points as well as point to where the client is. Any hints or links to some recourses would be appreciated).
Here is the Google Maps, Fusion Tables, and Geolocation code:
<script type="text/javascript">
(function() {
if(!!navigator.geolocation) {
var map;
var mapOptions = {
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP,
};
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
});
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions)
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col1",
from: "1JaRXQJ_YJch5Ua6cfZCBpaUEKRnd2jIcHVmcODY",
orderBy: 'ST_DISTANCE(col1, LATLNG("geolocate"))',
limit: 3,
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
} else {
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: new google.maps.LatLng(39.918487877955485, -98.30599773437501),
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
layer = new google.maps.FusionTablesLayer({
map: map,
heatmap: { enabled: false },
query: {
select: "col1",
from: "1JaRXQJ_YJch5Ua6cfZCBpaUEKRnd2jIcHVmcODY",
where: ""
},
options: {
styleId: 2,
templateId: 2
}
});
}
})();
google.maps.event.addDomListener(window, 'load', initialize);
</script>
I know this is messy. I don't know javascript.
I would like to know how to put the variable "geolocate" created by:
navigator.geolocation.getCurrentPosition(function(position) {
var geolocate = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
map.setCenter(geolocate);
});
Into the LATLNG place in:
var layer = new google.maps.FusionTablesLayer({
query: {
select: 'Address',
from: '15UY2pgiz8sRkq37p2TaJd64U7M_2HDVqHT3Quw',
orderBy: 'ST_DISTANCE(Address, LATLNG(37.4,-122.1))',
limit: 3
}
Any help is greatly appreciated.
This is just a basic javascript question ...
Make geolocate global, like var map;
var map;
var geolocate;
Remove var in front of your existing geolocate.
Then remove quotes around your usage of geolocate.
orderBy: 'ST_DISTANCE(col1, LATLNG(' + geolocate + ') )',
Related
I am trying to center and fit the boundaries of multiple geojson polygon features on my google.maps.Map.
See this non geojson fiddle recreating the effect i'm after.
Is there an easy Google Map API 3 function to do this for geojson data?
See my code below and fiddle here
var map;
window.initMap = function() {
var mapProp = {
center: new google.maps.LatLng(51.8948201,-0.7333298),
zoom: 17,
mapTypeId: 'satellite'
};
map = new google.maps.Map(document.getElementById("map"), mapProp);
map.data.loadGeoJson('https://api.myjson.com/bins/g0tzw');
map.data.setStyle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
var bounds = new google.maps.LatLngBounds();
map.fitBounds(bounds);
map.setCenter(bounds.getCenter());
}
I need expert pointers on cleanest and best way approach this.
See working demo of my code above in fiddle.
http://jsfiddle.net/joshmoto/fe2vworc/
I've included my geojson inline so you can see the polygons on the map.
Here is a quick example of how you can get your features bounds. This will just get each feature bounds, extend a LatLngBounds object and then fit the map with these bounds.
var map;
function initialize() {
map = new google.maps.Map(document.getElementById('map-canvas'), {
zoom: 10,
center: {
lat: 0,
lng: 0
}
});
var permits = {
type: "FeatureCollection",
id: "permits",
features: [{
type: "Feature",
properties: {
name: "Alpha Field"
},
geometry: {
type: "Polygon",
coordinates: [
[
[-0.72863, 51.895995],
[-0.730022, 51.896766],
[-0.730754, 51.896524],
[-0.731234, 51.896401],
[-0.731832, 51.896294],
[-0.732345, 51.896219],
[-0.732945, 51.896102],
[-0.732691, 51.895774],
[-0.732618, 51.895531],
[-0.732543, 51.895359],
[-0.73152, 51.894751],
[-0.731037, 51.894488],
[-0.730708, 51.894324],
[-0.72863, 51.895995]
]
]
}
},
{
type: "Feature",
properties: {
name: "Beta Field"
},
geometry: {
type: "Polygon",
coordinates: [
[
[-0.728004, 51.895658],
[-0.72863, 51.895995],
[-0.730708, 51.894324],
[-0.731217, 51.893784],
[-0.730992, 51.893709],
[-0.730793, 51.893567],
[-0.730734, 51.893435],
[-0.730761, 51.89333],
[-0.729696, 51.893244],
[-0.729391, 51.89314],
[-0.729249, 51.893586],
[-0.728991, 51.894152],
[-0.728525, 51.894983],
[-0.728004, 51.895658]
]
]
}
}
]
};
google.maps.event.addListenerOnce(map, 'idle', function() {
// Load GeoJSON.
map.data.addGeoJson(permits);
// Create empty bounds object
var bounds = new google.maps.LatLngBounds();
// Loop through features
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
geo.forEachLatLng(function(LatLng) {
bounds.extend(LatLng);
});
});
map.fitBounds(bounds);
});
}
initialize();
#map-canvas {
height: 150px;
}
<div id="map-canvas"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk"></script>
Props to #MrUpsidown for providing the working method to fitBounds.
I'm posting this answer to show my final solution based on #MrUpsidown answer using GeoJson data via loadGeoJson()
Here is my readable GeoJson here http://myjson.com/g0tzw
// initiate map
window.initMap = function() {
// permits json
var permits = 'https://api.myjson.com/bins/g0tzw';
// map properties
var mapProp = {
zoom: 17,
mapTypeId: 'satellite'
};
// google map object
var map = new google.maps.Map(document.getElementById("map"), mapProp);
// load GeoJSON.
map.data.loadGeoJson(permits, null, function () {
// create empty bounds object
var bounds = new google.maps.LatLngBounds();
// loop through features
map.data.forEach(function(feature) {
var geo = feature.getGeometry();
geo.forEachLatLng(function(LatLng) {
bounds.extend(LatLng);
});
});
// fit data to bounds
map.fitBounds(bounds);
});
// map data styles
map.data.setStyle({
strokeColor: '#FF0000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#FF0000',
fillOpacity: 0.35
});
}
I'm calling initMap via...
<script async defer src="https://maps.googleapis.com/maps/api/js?key=<?=$gmap_api?>&callback=initMap"></script>
See working demo here.
http://jsfiddle.net/joshmoto/eg3vj17m/
This question already has answers here:
How to set zoom level in google map
(6 answers)
Closed 8 years ago.
I have tried everything but can't work out how to remove the fit to bounds part of this code and set a zoom level instead. The problem is this map is designed for multiple markers but I'm currently only using it with 1 and it zooms in too close.
var gmarkers = [];
var markers = [
[ '<div id="mapcontent">' +
'<a href ="#project0"><h4>43 Short Street</h4>' +
'</div>'
, -27.686478,153.131745]
];
function initializeMaps() {
var myOptions = {
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{ featureType: 'all', stylers: [{saturation: -100},{brightness: 5} ]} ],
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
var infowindow = new google.maps.InfoWindow();
var marker, i;
var bounds = new google.maps.LatLngBounds();
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
for (i = 0; i < markers.length; i++) {
var pos = new google.maps.LatLng(markers[i][1], markers[i][2]);
bounds.extend(pos);
marker = new google.maps.Marker({
icon: './img/mapmarker.png',
position: pos,
map: map
});
gmarkers.push(marker);
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(markers[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
map.fitBounds(bounds);
}
initializeMaps()
function myClick(id){
google.maps.event.trigger(gmarkers[id], 'click');
}
Thanks for your help!
Change
map.fitBounds(bounds);
to (or remove it)
// map.fitBounds(bounds);
Add your desired zoom and center when you initialize the map:
var myOptions = {
// change these per your desired center and zoom.
zoom: 4,
center: new google.maps.LatLng(desiredLat, desiredLng),
mapTypeId: google.maps.MapTypeId.ROADMAP,
styles: [{
featureType: 'all',
stylers: [{
saturation: -100
},
{
brightness: 5
}]
}],
scrollwheel: false
};
var map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
But if you only have one marker, you should also remove the loop.
I need to plot multiple custom map markers using MapsV3 api either by an address or lat/lon. I put together the following code which works ok for lon/lat, but if the data contains an address the geocoder returns nothing. Any ideas on how to fix this.
$(document).ready(function () { initialize(); });
function initialize() {
var centerMap = new google.maps.LatLng(-27.0,133.0);
var options = {
panControl: false,
zoomControl: true,
scaleControl: false,
mapTypeControl: false,
streetViewControl: false,
zoom: 3,
center: centerMap,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map"), options);
var data = [
{
'title':'F C Building Construction ...',
'address':'',
'zindex':20,
'lat':'-33.797847',
'lon':'151.259928',
'marker_number':1,
'marker_html':' html content...',
'image': {
url:'//localhost/assets/images/markers/marker_1.png',
size: new google.maps.Size(24, 29),
origin: new google.maps.Point(0,0),
anchor: new google.maps.Point(10, 29)
}
}];
setMarkers(map, data);
var infowindow = new google.maps.InfoWindow();
}
function showMapPin(i) { }
function setMarkers(map,data) {
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < data.length; i++) {
setMarker(map, data[i], bounds);
}
map.fitBounds(bounds);
}
function setMarker(map, m, bounds) {
if(m["address"]!="") {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { "address": m["address"] }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
var siteLatLng = results[0].geometry.location;
}
});
} else {
var siteLatLng = new google.maps.LatLng(m["lat"], m["lon"]);
}
if(siteLatLng) {
var marker = new google.maps.Marker({
position: siteLatLng,
map: map,
//shadow: shadow,
icon: m["image"],
title: m["title"],
zIndex: m["zindex"],
html: m["marker_html"]
});
bounds.extend(siteLatLng);
google.maps.event.addListener(marker, "click", function() {
infowindow.setContent(this.html);
infowindow.open(map, this);
});
} // if latlng
}//]]>
After looking back over the code I realized that the variable siteLatLng is within geocode function scope so it never gets passed and it can't be returned. Setting the marker within this function works.
So i recently started to use Maps Api v3 and I am getting and undefined error when I try to make a nearby search. On this line var service_places = new google.maps.places.PlacesService(map);
function setupMap (position) {
// console.log(position);
var curLocation = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// console.log(curLocation);
var mapContainer = document.getElementById('map-container');
var mapOptions = {
zoom: 13,
center: curLocation,
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: true,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.DROPDOWN_MENU
}
};
map = new google.maps.Map(mapContainer,mapOptions);
var marker = new google.maps.Marker ({
position: curLocation,
map: map,
title: "I am here :)"
});
getNearMe(curLocation);
}
function getNearMe (curLocation) {
var request = {
loacation: curLocation,
radius: '10000',
types: ['bar', 'night_club']
};
var service_places = new google.maps.places.PlacesService(map);
service_places.nearbySearch(request,function (response,status) {
console.log(status);
console.log(response);
});
}
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=<MY-KEY>-fSUI&sensor=false">
</script>
You should include places library in your google api link.
Please try this in index.html:
<script src="http://maps.google.com/maps/api/js?sensor=true&libraries=places" type="text/javascript"></script>
I see a few errors off the bat. For example "location" is misspelled in your request variable.
You also should declare your map variable with "var map". But that's just a style issue. Fix these and see if it works and then we can troubleshoot more.
I want to import kml files that contains more than 2000 placemarks into googla map.
I use google api v3.
I can only show 200 placemarks.
I know that I can use more layers, but I want only one because I have to refresh it weekly and I don't want to split every time.
Thanks for your replays
THIS IS THE CODE:
<script>
var map;
function initialize() {
var mapOptions = {
zoom: 8,
center: new google.maps.LatLng(47.25,19.5),
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById('map-canvas'),
mapOptions);
loadKmlLayer(map);
}
function loadKmlLayer(map) {
var ctaLayer2 = new google.maps.KmlLayer('https://.../asdf.kml', {
suppressInfoWindows: false,
preserveViewport: false,
map: map
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
If your KML isn't very complex, you could try rendering it with a third-party KML parser (geoxml3 or geoxml-v3), see if that works (or points to the problem you are having with KmlLayer)
(function() {
window.onload = function() {
// Creating a new map
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(47.10,19.5),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
// Creating the JSON data
var json = [
DATA HERE LIKE:
{"title" :"City ZIP CODE STREET" , "lat" :47.2876 , "lng" :20.4978 ,"description" :"YOUR DESCRIPTION"},
]
// Creating a global infoWindow object that will be reused by all markers
var infoWindow = new google.maps.InfoWindow();
// Looping through the JSON data
for (var i = 0, length = json.length; i < length; i++)
{
var data = json[i],
latLng = new google.maps.LatLng(data.lat, data.lng);
// Creating a marker and putting it on the map
var marker = new google.maps.Marker({
position: latLng,
map: map,
title: data.title,
// icon: iconimage
});
// Creating a closure to retain the correct data, notice how I pass the current data in the loop into the closure (marker, data)
(function(marker, data) {
// Attaching a click event to the current marker
google.maps.event.addListener(marker, "click", function(e) {
infoWindow.setContent(data.description);
infoWindow.open(map, marker);
});
})
//OnClick event
(marker, data);
}
} })();