I have a map that shows 3 polygons and a route that passes a cross them. Each polygone has a title property. I would like to display a polygone title when the route passes by it.
This is the code I did :
<!doctype html><html class="no-js" lang="en">
<head>
<meta charset="utf-8">
<meta content="IE=edge,chrome=1" http-equiv="X-UA-Compatible">
<title>Loading / Editing Zones</title>
<style>
#map, html, body { padding: 0; margin: 0; height: 100%; } #panel { width: 200px; font-family: Arial, sans-serif; font-size: 13px; float: right; margin: 10px; } #delete-button { margin-top: 5px; } #login_close{ display: none; } .labels { color: red; background-color: white; font-family: "Lucida Grande", "Arial", sans-serif; font-size: 10px; font-weight: bold; text-align: center; width: 65px; border: 2px solid black; white-space: nowrap; } .autocomplete-suggestions { border: 1px solid #999; background: #FFF; overflow: auto; } .autocomplete-suggestion { padding: 2px 5px; white-space: nowrap; overflow: hidden; } .autocomplete-selected { background: #F0F0F0; } .autocomplete-suggestions strong { font-weight: normal; color: #3399FF; }
</style>
</head>
<body>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script src="http://maps.googleapis.com/maps/api/js?sensor=false&libraries=drawing,geometry" type="text/javascript"></script>
<script type="text/javascript">
var directionsDisplay = new google.maps.DirectionsRenderer(),
directionsService = new google.maps.DirectionsService(),
polys = new Array(),
map = null,
zoom = 10,
myPolygons =
[
{
"name": "zone1",
"coordinates": [
"51.44459,-0.21835",
"51.46256,-0.11261",
"51.43004,0.03708",
"51.40777,-0.09888",
"51.39064,-0.21149",
"51.40692,-0.27191"
]
},
{
"name": "zone2",
"coordinates": [
"51.56683,-0.22934",
"51.54292,-0.13046",
"51.57195,0",
"51.59755,-0.03708",
"51.5984,-0.13733",
"51.59755,-0.19913"
]
},
{
"name": "zone3",
"coordinates": [
"51.66148,-0.13733",
"51.61461,-0.08514",
"51.61887,0.02197",
"51.65381,0.05905",
"51.64359,-0.04807"
]
}
];
function drawPolygon(poly, polyLabel) {
var options = {
paths: poly,
strokeColor: '#AA2143',
strokeOpacity: 1,
strokeWeight: 2,
fillColor: "#FF6600",
fillOpacity: 0.7,
polyTitle: polyLabel
};
newPoly = new google.maps.Polygon(options);
newPoly.setMap(map);
polys.push(newPoly);
}
function sendPolygonForDrawing() {
for(var i =0; i<myPolygons.length; i++){
poly = new Array();
var coord = myPolygons[i].coordinates;
var lng = coord.length;
for(var j=0; j<lng; j++){
var longit_Latid = coord[j].split(',');
poly.push(new google.maps.LatLng(parseFloat(longit_Latid[0]), parseFloat(longit_Latid[1])));
}
drawPolygon(poly, myPolygons[i].name);
poly.pop();
}
}
//Route
function calcRoute() {
var start = "Croydon";
var end = "Cheshunt";
var waypts = [];
var waysArray = ["London"];
for (var i = 0; i < waysArray.length; i++) {
waypts.push({
location:waysArray[i],
stopover:true});
}
var request = {
origin: start,
destination: end,
waypoints: waypts,
optimizeWaypoints: true,
travelMode: google.maps.TravelMode.DRIVING
};
directionsService.route(request, function(response, status) {
if (status == google.maps.DirectionsStatus.OK) {
directionsDisplay.setDirections(response);
var routCoordinates = fncRouteZoneIntersection(response);//this function populates the routCoordinates with the JSON data of the route.
var exist = new Array();
for(var i=0; i<polys.length; i++){//polys holds all polygons objects.
for(var j=0; j<routCoordinates.length; j++){
if(google.maps.geometry.poly.containsLocation(new google.maps.LatLng(routCoordinates[j].k, routCoordinates[j].A), polys[i]) == true){
exist .push(polys.polyTitle);
break;
/*this breaks the loop checking when a point is found inside a polygon
and go check the next one, because knowing that one point of the route is
inside a polygon is enough*/
}
}
}
console.log(exist);
alert(exist);
}
});
directionsDisplay.setMap(map);
}
function fncRouteZoneIntersection(response){
var myRoute = response.routes[0].legs[0];
var lngLatCordinates = new Array();
for (var i = 0; i < myRoute.steps.length; i++) {
lngLatCordinates.push(myRoute.steps[i].start_point);
}
return lngLatCordinates;
}
$(function() {
//Basic
var cartodbMapOptions = {
zoom: zoom,
center: new google.maps.LatLng(51.465872, -0.065918),
disableDefaultUI: false,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
// Init the map
map = new google.maps.Map(document.getElementById("map"),cartodbMapOptions);
sendPolygonForDrawing();
calcRoute();
var drawingManager = new google.maps.drawing.DrawingManager({
drawingControl: false,
polygonOptions: {
fillColor: '#0099FF',
fillOpacity: 0.7,
strokeColor: '#AA2143',
strokeWeight: 2,
clickable: true,
zIndex: 1,
editable: true
}
});
});
</script>
<div id="map">
</div>
</body>
</html>
Sounds like my code starting from the line : var routCoordinates = fncRouteZoneIntersection(response);............ is only checking the starting, waypoint and the end of the route against the polygons and not all the route points that is why I get an empty array when doing the check.
Can any one help me please?
You have to use overview_path instead of route legs. See docs overview_path contains an array of LatLngs that represent an approximate (smoothed) path of the resulting directions.
function fncRouteZoneIntersection(response) {
console.log('fncRouteZoneIntersection...');
// var myRoute = response.routes[0].legs[0];
var myRoute = response.routes[0].overview_path;
var lngLatCordinates = new Array();
// for (var i = 0; i < myRoute.steps.length; i++) {
for (var i = 0; i < myRoute.length; i++) {
// lngLatCordinates.push(myRoute.steps[i].start_point);
lngLatCordinates.push(myRoute[i]);
}
// console.log(lngLatCordinates);
return lngLatCordinates;
}
and you have to change:
exist.push(polys.polyTitle);
to
exist.push(polys[i].polyTitle);
See example at jsbin with markers. List of polygon titles is written to console.log.
Related
I am trying to replicate the amcharts demo seen here:
https://www.amcharts.com/docs/v4/tutorials/using-mapchart-with-google-maps-api/
to only show Canada:
What is the best way to lock these two layers together like the amcharts world demo?
I have tried setting bounds, but the zoom scales don't line up. I'm sure there's an easier way that I'm simply not aware of.
var gmap;
function initGoogleMap() {
gmap = new google.maps.Map(document.getElementById("gmap"), {
scrollwheel: true,
center: new google.maps.LatLng(56.130366, -106.346771),
zoom: 3,
disableDefaultUI: true
});
var swBound = new google.maps.LatLng(41.6765556, -141.00275);
var neBound = new google.maps.LatLng(83.3362128, -52.3231981);
var bounds = new google.maps.LatLngBounds(swBound, neBound);
// google.maps.event.addListener(gmap, 'bounds_changed', updateMapPosition);
gmap.fitBounds(bounds);
}
var ammap = am4core.create("ammap", am4maps.MapChart);
ammap.geodata = am4geodata_canadaLow;
ammap.projection = new am4maps.projections.Mercator();
ammap.zoomDuration = 0;
ammap.homeZoomLevel = 0;
ammap.homeGeoPoint = {
latitude: 56.130366,
longitude: -106.346771
};
var polygonSeries = ammap.series.push(new am4maps.MapPolygonSeries());
polygonSeries.useGeodata = true;
ammap.zoomControl = new am4maps.ZoomControl();
var polygonTemplate = polygonSeries.mapPolygons.template;
polygonTemplate.tooltipText = "{name}";
polygonTemplate.fill = am4core.color("#74B266");
polygonTemplate.fillOpacity = 0.5;
var hs = polygonTemplate.states.create("hover");
hs.properties.fill = am4core.color("#367B25");
ammap.events.on("zoomlevelchanged", updateMapPosition);
ammap.events.on("mappositionchanged", updateMapPosition);
ammap.events.on("scaleratiochanged", updateMapPosition);
function updateMapPosition(ev) {
if ( typeof gmap === "undefined" )
return;
gmap.setZoom(Math.log2(ammap.zoomLevel) + 3);
gmap.setCenter( {
// a small adjustment needed for this div size:
lat: ammap.zoomGeoPoint.latitude,
lng: ammap.zoomGeoPoint.longitude
} );
}
#maps {
width: 1000px;
height: 500px;
border: 0px solid #eee;
margin: 0px auto;
position: relative;
}
.mapdiv {
width: 1000px;
height: 500px;
position: absolute;
top: 0;
left: 0;
}
<script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&callback=initGoogleMap" defer></script>
<script src="https://www.amcharts.com/lib/4/core.js?ver=5.9.2"></script>
<script src="https://www.amcharts.com/lib/4/maps.js?ver=5.9.2"></script>
<script type='text/javascript' src='https://cdn.amcharts.com/lib/4/geodata/canadaLow.js?ver=5.9.2' id='am-canada-js'></script>
<!-- HTML -->
<div id="maps">
<div id="gmap" class="mapdiv" style="visibility: visible;"></div>
<div id="ammap" class="mapdiv" style="visibility: visible;"></div>
</div>
I am creating a custom map using google maps which is showing direction from the A to B. I want to show all the possible routes from A to B. When adding a direction from A to B in a custom map it gives me only a one route. How can i get the all possible routes for a given destination from a starting point
You may set provideRouteAlternatives to true in the DirectionsRequest in order get multiple routes from the DirectionsResult object.
Here's what is stated in the documentation:
Generally, only one route is returned for any given request, unless the request's provideRouteAlternatives field is set to true, in which, multiple routes may be returned.
Then in order to display all the routes in your map, you may get the overview_path from each route and store it in a Polyline array and then pass that array to polylineOptions property of the DirectionsRenderer object.
Here's a sample code of what I'm suggesting.
Here's the embedded code as well
var map;
var polyOptions =[];
function initMap(){
var directionsService = new google.maps.DirectionsService();
var directionsDisplay = new google.maps.DirectionsRenderer();
map = new google.maps.Map(document.getElementById('map'), {
zoom: 7,
center: {lat: 41.85, lng: -87.65}
});
directionsDisplay.setMap(map);
document.getElementById('submit').addEventListener('click', function() {
removeLine(polyOptions);
polyOptions = [];
calculateAndDisplayRoute(directionsService,directionsDisplay);
});
}
function calculateAndDisplayRoute(directionsService,directionsDisplay) {
directionsService.route({
origin: document.getElementById('start').value,
destination: document.getElementById('end').value,
travelMode: 'DRIVING',
provideRouteAlternatives : true
}, function(response, status) {
if (status === 'OK') {
if (status === google.maps.DirectionsStatus.OK) {
var pathPoints ;
for(var i = 0; i<response.routes.length; i++){
var routeLeg = response.routes[i].legs[0];
pathPoints = response.routes[i].overview_path;
var polyPath = new google.maps.Polyline({
path: pathPoints,
strokeColor: "Blue",
strokeOpacity: 0.7,
strokeWeight: 5,
map: map
})
polyOptions.push(polyPath);
}
directionsDisplay.setDirections(response);
directionsDisplay.setOptions({
polylineOptions: polyOptions,
suppressPolylines : true
});
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
function removeLine(options) {
for(var i = 0; i < options.length; i++)
options[i].setMap(null);
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 100%;
}
/* Optional: Makes the sample page fill the window. */
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#floating-panel {
position: absolute;
top: 10px;
left: 25%;
z-index: 5;
background-color: #fff;
padding: 5px;
border: 1px solid #999;
text-align: center;
font-family: 'Roboto','sans-serif';
line-height: 30px;
padding-left: 10px;
}
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Multiple Routes</title>
</head>
<body>
<div id="floating-panel">
<strong>Start:</strong>
<input id="start" type="text" value="chicago">
<strong>End:</strong>
<input id="end" type="text" value="Oklahoma">
<input id="submit" type="button" value="Get Route">
<!-- <br> -->
</div>
<div id="map"></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB7fqfSyuj-jkh9cNGL63Jin5t4aHXIRUE&callback=initMap">
</script>
</body>
</html>
.
I'm having problems getting google's searchbox service to run properly for me.
What I have is a map with a polygon drawn on it. I would like to use the searchbox and/or autocomplete service to return ONLY business of the specified type (e.g. restaurants, fast food, warehouses, etc.) that are within this polygons boundaries.
I can use the nearby service to return results based on type or keyword. I can also get the searchbox to return results for restaurants; however, if I update the search to look for other businesses, such as warehouses, the map zooms out and shows warehouses all over the world.
Here is a working fiddle example:
<html>
<head>
<meta charset="utf-8">
<title>Transition Center Online</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<p>TODO: Add Google JavaScript Map with walkroute outline.</p>
<p>TODO: List walking times</p>
<p>TODO: List common walk routes and businesses</p>
<!-- where the map will live -->
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
function initMap() {
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
//keyword: ['restaurant']
}, callback);
var walkRouteBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
var options = {
bounds: walkRouteBounds,
strictBounds: true
};
// Create the search box and link it to the UI element.
var input = document.getElementById('pac-input');
var searchBox = new google.maps.places.SearchBox(input, options);
map.controls[google.maps.ControlPosition.TOP_CENTER].push(input);
var markers = [];
// Listen for the event fired when the user selects a prediction and retrieve
// more details for that place.
searchBox.addListener('places_changed', function() {
var places = searchBox.getPlaces();
searchBox.setBounds(walkRouteBounds);
if (places.length == 0) {
return;
}
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
// For each place, get the icon, name and location.
var bounds = new google.maps.LatLngBounds(
new google.maps.LatLng(37.673308, -97.352833),
new google.maps.LatLng(37.697636, -97.317306),
);
places.forEach(function(place) {
if (!place.geometry) {
console.log("Returned place contains no geometry");
return;
}
var icon = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
markers.push(new google.maps.Marker({
map: map,
//icon: icon,
title: place.name,
position: place.geometry.location
}));
if (place.geometry.viewport) {
// Only geocodes have viewport.
bounds.union(place.geometry.viewport);
} else {
bounds.extend(place.geometry.location);
}
});
map.fitBounds(bounds);
});
}
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
GoogleMap searchbox fiddle
EDIT: Alright so I have been able to come up with a solution using a dropdown box, although it is not ideal because I have to hard code my keywords.
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Walkroute Dropdown</title>
<meta name="description" content="">
<meta name="title" content="">
<meta name="author" content="WWRF">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<style>
#map {
height: 600px;
width: 100%;
}
#description {
font-family: Roboto;
font-size: 15px;
font-weight: 300;
}
#infowindow-content .title {
font-weight: bold;
}
#infowindow-content {
display: none;
}
#map #infowindow-content {
display: inline;
}
.pac-card {
margin: 10px 10px 0 0;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
background-color: #fff;
font-family: Roboto;
}
#pac-container {
padding-bottom: 12px;
margin-right: 12px;
}
.pac-controls {
display: inline-block;
padding: 5px 11px;
}
.pac-controls label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
#title {
color: #fff;
background-color: #4d90fe;
font-size: 25px;
font-weight: 500;
padding: 6px 12px;
}
#target {
width: 345px;
}
</style>
</head>
<body>
<div class="container">
<select name="mapchange" onchange="updateMap(this.options[this.selectedIndex].value)">
<option value="restaurants">Restaurants</option>
<option value="warehouses">Warehouses</option>
<option value="temp services">Temp Services</option>
</select>
<!-- where the map will live -->
<div id="map"></div>
</div>
<script>
// This example requires the Places library. Include the libraries=places
// parameter when you first load the API. For example:
// <script src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY&libraries=places">
var map;
var infowindow;
var wwrf = {
lat: 37.682319,
lng: -97.333311
};
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: wwrf,
zoom: 14
});
var squareCoords = [
{lat: 37.697465, lng: -97.341629},
{lat: 37.697636, lng: -97.317306},
{lat: 37.671759, lng: -97.317142},
{lat: 37.673308, lng: -97.352833},
{lat: 37.693239, lng: -97.352852}
];
// Construct the walkroute polygon.
var walkRoute = new google.maps.Polygon({
paths: squareCoords,
strokeColor: '#008000',
strokeOpacity: 0.8,
strokeWeight: 2,
fillColor: '#008000',
fillOpacity: 0.1
});
walkRoute.setMap(map);
infowindow = new google.maps.InfoWindow();
/*var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: ['restaurant']
}, callback);*/
}
var markers = [];
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location
});
// Create a marker for each place.
markers.push(marker);
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent('<strong>' + place.name + '</strong><br/>' + place.formatted_address);
infowindow.open(map, this);
});
}
function updateMap(selectControl) {
// Clear out the old markers.
markers.forEach(function(marker) {
marker.setMap(null);
});
markers = [];
var keyword = selectControl;
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: wwrf,
radius: 1600,
type: ['establishment'],
keyword: keyword
}, callback);
}
function clearMarkers() {
for (var i = 0; i < markersArray.length; i++ ) {
markersArray[i].setMap(null);
}
markersArray.length = 0;
}
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=your_api&libraries=places&callback=initMap" async defer></script>
</body>
</html>
And here's a link to the fiddle: Walkroute dropdown
I can see that you try to initialize the SearchBox with strictBounds: true option, but unfortunately, the SearchBox doesn't support strict bounds filter at current moment. If you can switch to the Autocomplete, it is indeed supports strict bounds and you can initialize the autocomplete like
var options = {
bounds: walkRouteBounds,
strictBounds: true,
types: ['establishment']
};
var input = document.getElementById('pac-input');
var autocomplete = new google.maps.places.Autocomplete(input, options);
Regarding the strict bounds for SearchBox, there is a feature request in Google issue tracker:
https://issuetracker.google.com/issues/67982212
Feel free to star the feature request to add your vote and subscribe to notifications.
Ok ,I've been looking to this for a while and here comes a possible solution that I thought:
So inside the For loop in the callback Function may I suggest before creating a marker to ask (with a IF and I think there is a method called contains that returns a boolean) if the
place.geometry.location is inside your bounds, so if the place is not inside your bounds then you do not create that marker, therefore the map won't zoom out.
Another solution would be forcing the zoom to a value after the autocomplete search.
I hope with this you could find a solution to your issue.
I am trying to add multiple markers from my javaFX application through the webengine.executescript() method .I have fallen the method in a loop to show all the markers but it just shows the last positioned marker .Here is my javaFx code for that
Button refresh = new Button("Refresh");
refresh.setOnAction(new EventHandler<ActionEvent>() {
#Override
public void handle(ActionEvent arg0) {
String[] latitude = {"23.806744","10"};
String[] longitude = {"90.3685549","20"};
//networking should be here
for (int i = 0; i < latitude.length; i++) {
lat = Double.parseDouble(latitude[i]);
lon = Double.parseDouble(longitude[i]);
System.out.printf("%.2f %.2f%n", lat, lon);
webEngine.executeScript("" +
"window.lat = " + lat + ";" +
"window.lon = " + lon + ";" +
"document.goToLocation(window.lat,window. lon);"
);
}
}
}
);
function initMap() {
var latlng = new google.maps.LatLng(35.857908, 10.598997);
var origin_place_id = null;
var destination_place_id = null;
var travel_mode = google.maps.TravelMode.DRIVING;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: -33.8688, lng: 151.2195},
zoom: 13
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer;
directionsDisplay.setMap(map);
var origin_input = document.getElementById('origin-input');
var destination_input = document.getElementById('destination-input');
var modes = document.getElementById('mode-selector');
map.controls[google.maps.ControlPosition.TOP_LEFT].push(origin_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(destination_input);
map.controls[google.maps.ControlPosition.TOP_LEFT].push(modes);
var origin_autocomplete = new google.maps.places.Autocomplete(origin_input);
origin_autocomplete.bindTo('bounds', map);
var destination_autocomplete =
new google.maps.places.Autocomplete(destination_input);
destination_autocomplete.bindTo('bounds', map);
function expandViewportToFitPlace(map, place) {
if (place.geometry.viewport) {
map.fitBounds(place.geometry.viewport);
} else {
map.setCenter(place.geometry.location);
map.setZoom(17);
}
}
origin_autocomplete.addListener('place_changed', function() {
var place = origin_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
origin_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
destination_autocomplete.addListener('place_changed', function() {
var place = destination_autocomplete.getPlace();
if (!place.geometry) {
window.alert("Autocomplete's returned place contains no geometry");
return;
}
expandViewportToFitPlace(map, place);
// If the place has a geometry, store its place ID and route if we have
// the other place ID
destination_place_id = place.place_id;
route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay);
});
function route(origin_place_id, destination_place_id, travel_mode,
directionsService, directionsDisplay) {
if (!origin_place_id || !destination_place_id) {
return;
}
directionsService.route({
origin: {'placeId': origin_place_id},
destination: {'placeId': destination_place_id},
provideRouteAlternatives: true,
travelMode: google.maps.DirectionsTravelMode.DRIVING
}, function(response, status) {
if (status === google.maps.DirectionsStatus.OK) {
for (var i = 0, len = response.routes.length; i < len; i++) {
new google.maps.DirectionsRenderer({
map: map,
directions: response,
routeIndex: i
});
}
} else {
window.alert('Directions request failed due to ' + status);
}
});
}
var marker = new google.maps.Marker({
position: new google.maps.LatLng(0,0),
map: map,
draggable: false,
title: "",
autoPan: false
});
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var latlng = new google.maps.LatLng(x, y);
marker.setPosition(latlng);
//map.setCenter(latLng);
}
}
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
width:100%;
}
.controls {
margin-top: 15px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#origin-input,
#destination-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 200px;
}
#origin-input:focus,
#destination-input:focus {
border-color: #4d90fe;
}
#mode-selector {
color: #fff;
background-color: #4d90fe;
margin-left: 12px;
padding: 5px 11px 0px 11px;
}
#mode-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
</head>
<body>
<input id="origin-input" class="controls" type="text"
placeholder="Enter an origin location">
<input id="destination-input" class="controls" type="text"
placeholder="Enter a destination location">
<div id="map"></div>
It would be nice if anyone could help
Your problem is you create your marker only once. You then call document.goToLocation in your loop, simply updating the position of that one marker every time. At the end of the loop, it has the position of the last of those locations.
If you want a marker on every location, create a marker inside the document.goToLocation function:
document.goToLocation = function(x, y) {
alert("goToLocation, x: " + x +", y:" + y);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(x, y),
map: map,
draggable: false,
title: "",
autoPan: false
});
}
I'm close to finishing this but I'm having a trouble with the Search box of gmaps.
The concept of the project is to type in a zip code(in my example a fixed one, 15124) and display on the map a number of markers(representing the stores in that area) and in a sidebar their names. The only problem I am facing is the auto-complete/getPlaces property that the search-box has. How do I get rid of this property? I just want a plain input text so that i can write the z.c. and then take that and compare it to see if it's true.Here's my code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<title>Store Locate</title>
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=false&libraries=places"></script>
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<script type="text/javascript">
var side_bar_html = "";
// arrays to hold copies of the markers and html used by the side_bar
var gmarkers = [];
var marker;
var map = null;
var t=1;
function initialize() {
// create the map
var myOptions = {
zoom: 11,
center: new google.maps.LatLng(37.9833333, 23.7333333),
mapTypeControl: true,
mapTypeControlOptions:{style:google.maps.MapTypeControlStyle.DROPDOWN_MENU},
navigationControl: true,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById("map_canvas"),myOptions);
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
initSearchBox(map, 'pac-input');
}//----------------INIT END--------------------
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50)
});
// This function picks up the click and opens the corresponding info window
function myclick(i) {
google.maps.event.trigger(gmarkers[i], "click");
}
function initSearchBox(map, controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var infowindow = new google.maps.InfoWindow(
{
size: new google.maps.Size(150,50),
content : place.info
});
// Add markers to the map
// Set up the markers with info windows
// add the points
if ((document.getElementById(controlId).value) == ("Marousi, 15124, Vorios Tomeas Athinon, Greece" ||(document.getElementById(controlId).value) == 15124) && t==1){
var point = new google.maps.LatLng(38.0397739,23.8004445);
var marker = createMarker(point,"Relay Marketing","<b>Relay Marketing Services</b> <br>Vlahernon 10,15124,Marousi<br>211 411 2311")
var point = new google.maps.LatLng(38.0409333,23.7954601);
var marker = createMarker(point,"Nespresso S.A.","<b>Nespresso S.A.</b><br>Agiou Thoma 27,15124,Marousi")
var point = new google.maps.LatLng(38.0473031,23.8053483);
var marker = createMarker(point,"Regency Entertainment","<b>Regency Entertainment</b><br>Agiou Konstantinou 49,15124,Marousi <br>210 614 9800")
var point = new google.maps.LatLng(38.050986,23.8084322);
var marker = createMarker(point,"Just4U","<b>Just4U</b> <br>Dimitriou Gounari 84, 15124, Marousi<br>210 614 1923")
var point = new google.maps.LatLng(38.0400533,23.8011982);
var marker = createMarker(point,"Ekka Cars S.A.","<b>Ekka</b> <br>Leoforos Kifisias 79,15124,Marousi<br>210 349 8000")
// put the assembled side_bar_html contents into the side_bar div
document.getElementById("side_bar").innerHTML = side_bar_html;
t -=1;//This is so if you search again, it doesn't display again in sidebar
}
map.fitBounds(place.geometry.viewport);
});
}
// A function to create the marker and set up the event window function
function createMarker(latlng, name, html) {
var contentString = html;
var marker = new google.maps.Marker({
position: latlng,
map: map,
//zIndex: Math.round(latlng.lat()*-100000)<<5
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.setContent(contentString);
infowindow.open(map,marker);
});
// save the info we need to use later for the side_bar
gmarkers.push(marker);
// add a line to the side_bar html
side_bar_html += '<a href="javascript:myclick(' + (gmarkers.length-1) + ')">' + name + '<\/a><br>';
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style="margin:0px; padding:0px;" >
<input id="pac-input" class="controls" type="text" placeholder="Ταχυδρομικός κωδικός">
<table border="1">
<tr>
<td>
<div id="map_canvas" style="width: 550px; height: 450px"></div>
</td>
<td valign="top" style="width:160px; text-decoration: underline; color: #4444ff;">
<div id="side_bar"></div> <hr/>
</td>
</tr>
</table>
</body>
</html>
How to add search box
1 Ensure Places Library is loaded, for example:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?libraries=places"></script>
Note: To use the functionality contained within this library, you must
first load it using the libraries parameter in the Maps API bootstrap
URL: libraries=places
Create the search box and link it to the UI element.
HTML:
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
JavaScript:
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
3 Initialize Search Box control:
function initSearchBox(map,controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location
});
map.fitBounds(place.geometry.viewport);
});
}
Example
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(40.714364, -74.005972),
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions);
var locations = [
['New York', 40.714364, -74.005972, 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png']
];
var infowindow = new google.maps.InfoWindow();
google.maps.event.addListener(map, 'click', function () {
infowindow.close();
});
var markers = [];
for (var i = 0; i < locations.length; i++) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map,
icon: locations[i][3]
});
google.maps.event.addListener(marker, 'click', (function (marker, i) {
return function () {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
markers.push(marker);
}
initSearchBox(map, 'pac-input');
}
function initSearchBox(map, controlId) {
// Create the search box and link it to the UI element.
var input = (document.getElementById(controlId));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(input);
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function () {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
//get first place
var place = places[0];
var marker = new google.maps.Marker({
map: map,
title: place.name,
position: place.geometry.location,
icon: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/green-dot.png'
});
map.fitBounds(place.geometry.viewport);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px;
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
I found this example on Google website, it's an complete HTML file :
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<style>
html, body, #map-canvas {
height: 100%;
margin: 0px;
padding: 0px
}
.controls {
margin-top: 16px;
border: 1px solid transparent;
border-radius: 2px 0 0 2px;
box-sizing: border-box;
-moz-box-sizing: border-box;
height: 32px;
outline: none;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.3);
}
#pac-input {
background-color: #fff;
font-family: Roboto;
font-size: 15px;
font-weight: 300;
margin-left: 12px;
padding: 0 11px 0 13px;
text-overflow: ellipsis;
width: 400px;
}
#pac-input:focus {
border-color: #4d90fe;
}
.pac-container {
font-family: Roboto;
}
#type-selector {
color: #fff;
background-color: #4d90fe;
padding: 5px 11px 0px 11px;
}
#type-selector label {
font-family: Roboto;
font-size: 13px;
font-weight: 300;
}
</style>
<title>Places search box</title>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&signed_in=true&libraries=places"></script>
<script>
// This example adds a search box to a map, using the Google Place Autocomplete
// feature. People can enter geographical searches. The search box will return a
// pick list containing a mix of places and predicted search terms.
function initialize() {
var markers = [];
var map = new google.maps.Map(document.getElementById('map-canvas'), {
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var defaultBounds = new google.maps.LatLngBounds(
new google.maps.LatLng(-33.8902, 151.1759),
new google.maps.LatLng(-33.8474, 151.2631));
map.fitBounds(defaultBounds);
// Create the search box and link it to the UI element.
var input = /** #type {HTMLInputElement} */(
document.getElementById('pac-input'));
map.controls[google.maps.ControlPosition.TOP_LEFT].push(input);
var searchBox = new google.maps.places.SearchBox(
/** #type {HTMLInputElement} */(input));
// [START region_getplaces]
// Listen for the event fired when the user selects an item from the
// pick list. Retrieve the matching places for that item.
google.maps.event.addListener(searchBox, 'places_changed', function() {
var places = searchBox.getPlaces();
if (places.length == 0) {
return;
}
for (var i = 0, marker; marker = markers[i]; i++) {
marker.setMap(null);
}
// For each place, get the icon, place name, and location.
markers = [];
var bounds = new google.maps.LatLngBounds();
for (var i = 0, place; place = places[i]; i++) {
var image = {
url: place.icon,
size: new google.maps.Size(71, 71),
origin: new google.maps.Point(0, 0),
anchor: new google.maps.Point(17, 34),
scaledSize: new google.maps.Size(25, 25)
};
// Create a marker for each place.
var marker = new google.maps.Marker({
map: map,
icon: image,
title: place.name,
position: place.geometry.location
});
markers.push(marker);
bounds.extend(place.geometry.location);
}
map.fitBounds(bounds);
});
// [END region_getplaces]
// Bias the SearchBox results towards places that are within the bounds of the
// current map's viewport.
google.maps.event.addListener(map, 'bounds_changed', function() {
var bounds = map.getBounds();
searchBox.setBounds(bounds);
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<style>
#target {
width: 345px;
}
</style>
</head>
<body>
<input id="pac-input" class="controls" type="text" placeholder="Search Box">
<div id="map-canvas"></div>
</body>
</html>
I hope it will be useful...
Source : https://developers.google.com/maps/documentation/javascript/examples/places-searchbox