Have a map that I made using Google Maps API and Fusion Tables. I am trying to change the appearance of the markers on the map.
When I add the "styles", https://developers.google.com/maps/documentation/javascript/fusiontableslayer my map will not load on the page, and I get an error in my console reading: "unexpected identifier - styles"
Can someone help me figure out what I am doing wrong?
Here is my code:
var map, layer;
var geocoder;
function initialize(location) {
console.log(location);
geocoder = new google.maps.Geocoder();
var userlocation = new google.maps.LatLng(location.coords.latitude, location.coords.longitude);
map = new google.maps.Map(document.getElementById('map-canvas'), {
center: userlocation,
zoom: 8
});
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'Geocodable address\'',
from: '1x265dMvUClEGEVHD_3VRBvSRXk-mbs4jcO2xy29K',
}
styles: [
{markerOptions:{ iconName:"star"}}
]
});
layer.setMap(map);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
navigator.geolocation.getCurrentPosition(initialize);
I believe you're missing a comma before styles
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'Geocodable address\'',
from: '1x265dMvUClEGEVHD_3VRBvSRXk-mbs4jcO2xy29K',
}, //need a comma here
styles: [{...
You are missing a "," before styles:
layer = new google.maps.FusionTablesLayer({
query: {
select: '\'Geocodable address\'',
from: '1x265dMvUClEGEVHD_3VRBvSRXk-mbs4jcO2xy29K',
},
styles: [
{markerOptions:{ iconName:"star"}}
]
});
Related
I am trying to recreate the following map, made using Google MyMaps, by using Google Maps API
Anyone know the best way to do this? Have the following code at the moment but doesn't look great
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Search for up to 200 places with Radar Search</title>
<style>
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
</style>
<script>
var map;
var infoWindow;
var service;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: {
lat: 54.607868,
lng: -5.926437
},
zoom: 10,
styles: [{
stylers: [{
visibility: 'simplified'
}]
}, {
elementType: 'labels',
stylers: [{
visibility: 'off'
}]
}]
});
infoWindow = new google.maps.InfoWindow();
service = new google.maps.places.PlacesService(map);
// The idle event is a debounced event, so we can query & listen without
// throwing too many requests at the server.
map.addListener('idle', performSearch);
}
function performSearch() {
var request = {
bounds: map.getBounds(),
keyword: 'best view'
};
service.radarSearch(request, callback);
}
function callback(results, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
for (var i = 0, result; result = results[i]; i++) {
addMarker(result);
}
}
function addMarker(place) {
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
icon: {
url: 'https://developers.google.com/maps/documentation/javascript/images/circle.png',
anchor: new google.maps.Point(10, 10),
scaledSize: new google.maps.Size(10, 17)
}
});
google.maps.event.addListener(marker, 'click', function() {
service.getDetails(place, function(result, status) {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
console.error(status);
return;
}
infoWindow.setContent(result.name);
infoWindow.open(map, marker);
});
});
}
</script>
</head>
<body>
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCIcOfMnc85XkuJmotWkLL4mthAHqlUuWA&callback=initMap&libraries=places,visualization" async defer></script>
</body>
</html>
use a saved google my maps and share it from your google drive
Hi I'm using google documentation in geocoding service.
The script should display the location Casablanca but it still show the default location in austalia
The problem is that geocoder.geocode(...) is not executed
function initMap() {
var geocoder = new google.maps.Geocoder();
var map = new google.maps.Map(document.getElementById('map'), {
center: {lat: -34.397, lng: 150.644},
scrollwheel: false,
zoom: 8,
});
codeAddress(geocoder,map);
}
function codeAddress(geocoder, map)
{
var addr = "Casablanca";
geocoder.geocode( {'addr':addr}, function(results, status)
{
if (status == google.maps.GeocoderStatus.OK)
{
map.setCenter(results[0].geometry.addr);//center the map over the result
//place a marker at the location
var marker = new google.maps.Marker(
{
map: map,
position: results[0].geometry.addr
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
PS:
I'm using GooglMapper https://github.com/bradcornford/Googlmapper
I appreciate any help.
geocoder.geocode( {'addr':addr}, function(results, status)
Should be:
geocoder.geocode( {'address':addr}, function(results, status)
The GeocoderRequest object literal contains the following fields:
{
address: string,
location: LatLng,
placeId: string,
bounds: LatLngBounds,
componentRestrictions: GeocoderComponentRestrictions,
region: string
}
Taken from the documentation
Answer For my problem
map.setCenter(results[0].geometry.addr);
Should be
map.setCenter(results[0].geometry.location);
And
position: results[0].geometry.addr
Should Be
position: results[0].geometry.location
I have this code that allows the user to enter two cities, and shows the location of the given inputs. But what I want is to show as well the direction from the 1st city to the other. How to do that?
Here is my practice code:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?key=AIzaSyBQ8OCC8En5vNHod25Ov3Qs5E1v7NPRSsg&sensor=true">
</script>
<script type="text/javascript">
var geocoder;
var map;
function initialize1() {
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 8,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function initialize() {
// add mapOptions here to the values in the input boxes.
var mapOptions = {
center: new google.maps.LatLng(-34.397, 100.644),
zoom: 12,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),mapOptions);
geocoder = new google.maps.Geocoder();
addAddress(document.getElementById('from').value);
addAddress(document.getElementById('to').value);
}
function addAddress(place) {
var address = place;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
</script>
</head>
<body>
From: <input id="from" type="text" name="From"><br>
To: <input id="to" type="text" name="To"><br>
<button type="button" onclick="initialize()">View example (map-simple.html)</button>
<div id="map_canvas" style="width:100%; height:100%"></div>
</body>
</html>
thanks
Jason
Use the DirectionsService in the Google Maps API v3. Here is an example from the documentation:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-simple
and with text directions:
https://google-developers.appspot.com/maps/documentation/javascript/examples/directions-panel
if you mean the "location" means the address you can use the direction renderer like below to get the direction.
First of all store the location address of the two markers into the two text boxes if you want to display the to and from address with id's #from and #destination then follow the below code
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
Explanation : At first I created two markers of different locations and different data then after the dragend of any marker there will be infowindow that shows the address and two buttons start and finish. I think you have done upto this part .
So after this I used two text boxes which will be filled according to the start button or finish button clicked .
After this if the user clicks the find button this text boxes values are used to find the direction between the two markers
Note: "here you can any marker for from or to only difference you have to maintain is to change the button clicked that is start or finish ....."
"You can even directly give the address in the text boxes and find the directions between them"
Here for whole manipulation I used gmap3 here is the code below that might help you
<script type="text/javascript">
window.onload = clear;
function clear() {
$("#from").val(null)
$("#destination").val(null)
}
$(document).ready(function () {
var starting = "";
var finishing = "";
$("#find").click(function () {
starting = $("#from").val();
finishing = $("#destination").val();
$("#map").gmap3(
{
action: 'getRoute',
options: {
origin: starting,
destination: finishing,
travelMode: google.maps.DirectionsTravelMode.DRIVING
},
callback: function (results) {
if (!results) {
alert("returning")
return
};
$(this).gmap3(
{
action: 'addDirectionsRenderer',
options: {
preserveViewport: true,
draggable: false,
directions: results
}
}
);
}
})
})
$("#map").gmap3({
action: 'addMarkers',
markers: [ //markers array
{lat: 22.74, lng: 83.28, data: 'madhu' },
{ lat: 17.74, lng: 82.28, data: 'raghu' }
],
map: { // this is for map options not for any markers
center: [17.74, 83.28],
zoom: 5
},
marker: {
options: {
draggable: true
},
events: {// marker events
dragend: function (marker, event, data) {
var contentString = '<div id="main content">'
+ '<input type="button" id="start" value="start" />'
+ '<input type="button" id="finish" value="finish" />'
+ '</div>';
//get address on click event
$(this).gmap3({
action: 'getAddress',
latLng: marker.getPosition(),
callback: function (results) {
var map = $(this).gmap3('get'),
infowindow = $(this).gmap3({ action: 'get', name: 'infowindow' })
if (infowindow) {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
infowindow.open(map, marker);
infowindow.setContent(content + contentString);
}
else {
content = results && results[1] ? results && results[1].formatted_address : 'no address';
$(this).gmap3({
action: 'addinfowindow',
anchor: marker,
options: { content: content + contentString },
events: {
domready: function () {
$("#start").click(function () {
alert("start clicked " + content);
$("#from").val(content);
starting = content;
check();
})
$("#finish").click(function () {
alert("finish clicked " + content);
$("#destination").val(content);
finishing = content;
})
}
}
});
}
}
});
},
}
},
});
});
</script>
here is the html part for the above
<div id="headinput">
<input type="text" value="enter from" id="from" />
<input type="text" value="enter destination" id="destination" />
<input type="button" value="find" id="find" />
</div>
<br />
<div id ="map"style="width: 100%; top: auto; left: auto; position: relative; height: 600px; float:left" ></div>
This is perfectly worked one I checked it in firefox browser........:D
I wonder whether someone may be able to help me please.
I'm using the code below to perform an Google Maps Autocomplete action upon a user entering address details:
// JavaScript Document
var geocoder;
var map;
var marker;
function initialize(){
var myOptions = {
zoom: 6,
center: new google.maps.LatLng(54.312195845815246, -4.45948481875007),
mapTypeId: google.maps.MapTypeId.TERRAIN,
mapTypeControl: true,
mapTypeControlOptions: {
style: google.maps.MapTypeControlStyle.HORIZONTAL_BAR,
position: google.maps.ControlPosition.TOP_RIGHT
},
navigationControl: true,
navigationControlOptions: {
style: google.maps.NavigationControlStyle.ZOOM_PAN,
position: google.maps.ControlPosition.TOP_LEFT
},
scaleControl: true,
scaleControlOptions: {
position: google.maps.ControlPosition.BOTTOM_LEFT
}
};
map = new google.maps.Map(document.getElementById('map'), myOptions);
geocoder = new google.maps.Geocoder();
marker = new google.maps.Marker({
map: map,
draggable: true
});
}
$(document).ready(function() {
initialize();
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#osgb36lat").val(ui.item.latitude);
$("#osgb36lon").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
marker.setPosition(location);
map.setZoom(16);
map.setCenter(location);
}
});
});
google.maps.event.addListener(marker, 'dragend', function() {
geocoder.geocode({'latLng': marker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#osgb36lat').val(marker.getPosition().lat());
$('#osgb36lon').val(marker.getPosition().lng());
var point = marker.getPosition();
map.panTo(point);
}
}
});
});
})
and this is how I place it within my form.
<div>
<input name="address" type="text" id="address" size="40" maxlength="40" style="font:Calibri; font-size:12px" />
</div>
What I'd now like to be able to do is limit the number of items viewable in the list. I've done some research on several forums and on the Google Maps site but I can't seem to find a solution, so I'm not even sure whether this is possible.
I just wondered whether someone could possibly have a look at this please and provide a little guidance on how I may be able to go about this.
Many thanks and kind regards
The Google Maps V3 API now incudes an autocomplete feature that will adapt any text input field to autocomplete locations &/or Places. It doesn't show thumbnails yet but the addition of Places will be great for some use cases, here's the details:
Documentation: http://code.google.com/apis/maps/documentation/javascript/places.html#places_autocomplete
Reference: http://code.google.com/apis/maps/documentation/javascript/reference.html#Autocomplete
Example: http://code.google.com/apis/maps/documentation/javascript/examples/places-autocomplete.html
I think these will help you.....
After some further research, I found a great tutorial here: http://rjshade.com/2012/03/27/Google-Maps-autocomplete-with-jQuery-UI/ which I've been able to adapt.
Ok, this Question is 2 fold:
I would like to display an overlay showing counties on the google map...how can I do this?
I would like to get the county based off lat/lng when a marker is dynamically created.
I think question 2 is a bit more involved. Here is the code that I have thus far. Basically...a "job Marker" is created in 3 ways:
a. User types in address---address is geocoded, marker is set
b. user double clicks on the map and marker is set---address is reversed geocoded
3. user drags default marker to new area on map---marker set----address is reversed geocoded.
Here is the code:
initialize();
//Function for the autocomplete field for map
$(function() {
$("#address").autocomplete({
//This bit uses the geocoder to fetch address values
source: function(request, response) {
geocoder.geocode( {'address': request.term + ', us' }, function(results, status) {
response($.map(results, function(item) {
return {
label: item.formatted_address,
value: item.formatted_address,
latitude: item.geometry.location.lat(),
longitude: item.geometry.location.lng()
}
}));
})
},
//This bit is executed upon selection of an address
select: function(event, ui) {
$("#latitude").val(ui.item.latitude);
$("#longitude").val(ui.item.longitude);
var location = new google.maps.LatLng(ui.item.latitude, ui.item.longitude);
jobMarker.setPosition(location);
map.setCenter(location);
}
});
});
//when user drags job marker the new info is added.
google.maps.event.addListener(jobMarker, 'drag', function() {
geocoder.geocode({'latLng': jobMarker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(jobMarker.getPosition().lat());
$('#longitude').val(jobMarker.getPosition().lng());
}
}
});
});
google.maps.event.addListener(map, "dblclick", function(event)
{
// display the lat/lng in your form's lat/lng fields
var location = new google.maps.LatLng(event.latLng.lat(), event.latLng.lng());
jobMarker.setPosition(location);
geocoder.geocode({'latLng': jobMarker.getPosition()}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
$('#address').val(results[0].formatted_address);
$('#latitude').val(jobMarker.getPosition().lat());
$('#longitude').val(jobMarker.getPosition().lng());
}
}
});
});
First you can use Google Map Overlay to draw an overlay.
Second using the Geocoding Request you can get back an Response that contains an Address (which should include a County)
Update
Here is an example from the Geocoding Requestion link above:
{
"types":["sublocality","political"],
"formatted_address":"Winnetka, California, USA",
"address_components":
[
{
"long_name":"Winnetka",
"short_name":"Winnetka",
"types":["sublocality","political"]
},
{
"long_name":"Los Angeles",
"short_name":"Los Angeles",
"types":["administrative_area_level_3","political"]
},
{
"long_name":"Los Angeles",
"short_name":"Los Angeles",
"types":["administrative_area_level_2","political"]
},
{
"long_name":"California",
"short_name":"CA",
"types":["administrative_area_level_1","political"]
},
{
"long_name":"United States",
"short_name":"US",
"types":["country","political"]
}],
"geometry":{
"location": [34.213171,-118.571022],
"location_type":"APPROXIMATE"
}
}
"address_components" is an Array of Object that contains properties long_name, short_name and types. "types" is an Array of string that contains values describing the long_name and short_name. It appears you have to loop through each address_components looking for an Object where it's types has a string value of "administrative_area_level_2".