Display regions in google maps API - google-maps

So, I want to get a region of 'Lampung' but it is displayed as a region, not markers. My code is using geochart API. Here is my code :
google.load('visualization', '1', {'packages': ['geochart']});
google.setOnLoadCallback(drawMarkersMap);
function drawMarkersMap() {
var data = google.visualization.arrayToDataTable([
['Province'],
['Lampung'],
['Banten'],
]);
var options = {
region: '035', //South-East Asia
displayMode: 'regions',
colorAxis: {colors: ['#00853f', 'blue', '#e31b23']},
};
var chart = new google.visualization.GeoChart(document.getElementById('chart_div'));
chart.draw(data, options);
};
But the problem is, the result doesn't show any regions yet. It's just a map without any displayMode. Next problem is, if I add this to 'options':
resolution: 'provinces'
The result is just a blank web without the map. What's wrong here?

I think your region '035' is too large, you should zoom your region to a smaller area, in your case, you should use options['region'] = 'ID';
You can try with the below code, it should show 2 orange regions in your map:
<html>
<head>
<script type='text/javascript' src='https://www.google.com/jsapi'></script>
<script type='text/javascript'>
google.load('visualization', '1', {'packages': ['geomap']});
google.setOnLoadCallback(drawMap);
function drawMap() {
var data = google.visualization.arrayToDataTable([
['Province'],
['Lampung'],
['Banten']
]);
var options = {};
options['region'] = 'ID';
options['colors'] = [0xFF8747, 0xFFB581, 0xc06000]; //orange colors
options['dataMode'] = 'regions';
var container = document.getElementById('map_canvas');
var geomap = new google.visualization.GeoMap(container);
geomap.draw(data, options);
};
</script>
</head>
<body>
<div id='map_canvas'></div>
</body>
</html>

Related

Limit autocomplete results within the bounds of a place_id

I have two textboxes, both of which are autocompletes. The first one we get the place_id when I change it. Second textbox is supposed to suggest results within the place_id of the first.
Here's my code:
const options = {
types: ['(regions)'],
componentRestrictions: {country: 'gb'},
};
const search = new google.maps.places.Autocomplete( $("#address_1")[0], options);
google.maps.event.addListener(search, 'place_changed', function () {
var place = search.getPlace();
const options_b = {
types: ['(regions)'],
componentRestrictions: {country: 'gb'},
};
var options_2 = {
types: ['address'],
strictbounds: true,
radius:500,
//other parameters here..perhaps place_id ?
};
const search = new google.maps.places.Autocomplete( $("#address_2")[0], options_b);
});
So let's say I typed London in the first text box, then the 2nd text box should only suggest places within London.
If you want to limit the result of an Autocomplete to the bounds of a place, use the bounds of that place to restrict the Autocomplete and set the strictBounds: true option (note the capitalization)
const search1 = new google.maps.places.Autocomplete($("#address_1")[0], options);
google.maps.event.addListener(search1, 'place_changed', function() {
var place = search1.getPlace();
var bounds = place.geometry.viewport; // bounds of place returned by the first autocomplete
var options_2 = {
types: ['address'],
strictBounds: true,
bounds: bounds
};
const search2 = new google.maps.places.Autocomplete($("#address_2")[0], options_2);
});
proof of concept fiddle
"use strict";
// 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=AIzaSyCPJpjD-qcR_yIxJnS8maR5W9KB0E3EzYI&libraries=places">
function initAutocomplete() {
var map = new google.maps.Map(document.getElementById('map'))
const options = {
types: ['(regions)'],
componentRestrictions: {
country: 'gb'
},
};
const search1 = new google.maps.places.Autocomplete($("#address_1")[0], options);
google.maps.event.addListener(search1, 'place_changed', function() {
var place = search1.getPlace();
var bounds = place.geometry.viewport;
var marker = new google.maps.Marker({
position: place.geometry.location,
map: map
});
var rectangle = new google.maps.Rectangle({
bounds: bounds,
map: map
})
map.fitBounds(bounds);
var options_2 = {
types: ['address'],
strictBounds: true,
bounds: bounds
//other parameters here..perhaps place_id ?
};
const search2 = new google.maps.places.Autocomplete($("#address_2")[0], options_2);
google.maps.event.addListener(search2, 'place_changed', function() {
var place = search2.getPlace();
var marker = new google.maps.Marker({
position: place.geometry.location,
map: map,
icon: {
url: "https://maps.gstatic.com/intl/en_us/mapfiles/markers2/measle.png",
size: new google.maps.Size(7, 7),
anchor: new google.maps.Point(3.5, 3.5)
}
});
});
});
}
/* Always set the map height explicitly to define the size of the div
* element that contains the map. */
#map {
height: 80%;
}
/* Optional: Makes the sample page fill the window. */
html,
body {
height: 100%;
margin: 0;
padding: 0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>Place Autocomplete</title>
<script src="https://polyfill.io/v3/polyfill.min.js?features=default"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCkUOdZ5y7hMm0yrcCQoCvLwzdM6M8s5qk&callback=initAutocomplete&libraries=places&v=weekly" defer></script>
<!-- jsFiddle will insert css and js -->
</head>
<body>
<div class="pac-card" id="pac-card">
<div id="pac-container">
<input id="address_1" type="text" placeholder="Enter a location" /><br/>
<input id="address_2" type="text" placeholder="Enter a location" />
</div>
</div>
<div id="map"></div>
</body>
</html>

google geocharts make clickable countries and change color of selected countries

I am using geochart from google for my website, but I want the countries to be clickable. When I click one country it's colour to be changed and stay selected while selecting other countries.
I need to make geochart like in following url:
HTML
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="regions_div" style="width: 900px; height: 500px;"></div>
JS
google.charts.load('current', {
'packages':['geochart'],
// Note: you will need to get a mapsApiKey for your project.
// See: https://developers.google.com/chart/interactive/docs/basic_load_libs#load-settings
'mapsApiKey': 'AIzaSyD-9tSrke72PouQMnMX-a7eZSW0jkFMBWY'
});
google.charts.setOnLoadCallback(drawRegionsMap);
function drawRegionsMap() {
var data = google.visualization.arrayToDataTable([
['Country', 'Popularity'],
['Germany', 200],
['United States', 300],
['Brazil', 400],
['Canada', 500],
['France', 600],
['RU', 700],
['India', 700]
]);
var options = {};
var chart = new google.visualization.GeoChart(document.getElementById('regions_div'));
chart.draw(data, options);
}
JS FIDDLE
Selecting countries on a map

Google places api I want to get JSON output

I want to search for locations in a particular place on the google places api and display them on JSOn output.Suppose I want to search for all the banks my near place. How do I code for that.Can you please give sample code.
try this working code..it uses jquery mobile. it finds the places around your current lat & lon.
map.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="css/jquery.mobile-1.0.min.css" />
<script src="js/jquery.js"></script>
<script src="js/jquery.mobile-1.0.js"></script>
<script src="js/map.js"></script>
<script type="text/javascript" src="//maps.googleapis.com/maps/api/js?sensor=true&libraries=places"></script>
</head>
<body>
<div data-role="page" data-theme="none" class="page-map" id="page-map">
<script src="js/canvas.js"></script>
<div id="map-canvas">
<!-- map loads here... -->
</div>
</div>
</body>
</html>
map.js
var map;
var infowindow;
var lat;
var lng;
var lng;
var service;
var reference;
var initialLocation;
$( '.page-map' ).live( 'pagecreate',function(event){
checkLocation();
});
function checkLocation() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
initialLocation = new google.maps.LatLng(position.coords.latitude,
position.coords.longitude);
lat = position.coords.latitude;
lng = position.coords.longitude;
callPlaceService(lat, lng);
}, gpsFail, {
enableHighAccuracy : true,
maximumAge : 300000
});
}
}
function callPlaceService(lat, lng) {
var pyrmont = new google.maps.LatLng(lat, lng);
var myOptions = {
zoom : 15,
center : pyrmont,
mapTypeId : google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map-canvas"), myOptions);
var request = {
location : pyrmont,
radius : 5000,
//types: ['atm','bank'],
keyword : 'Bank'
};
service = new google.maps.places.PlacesService(map);
service.search(request, callback);
}
function callback(results, status) {
if (status == google.maps.places.PlacesServiceStatus.OK) {
for ( var i = 0; i < results.length; i++) {
var requestDetails = {reference : results[i].reference};
service.getDetails(requestDetails, checkDetailedStatus);
}
}
}
function checkDetailedStatus(details, detailStatus) {
if (detailStatus == google.maps.places.PlacesServiceStatus.OK) {
var name = '{"name":"'+ details.name +'"}';
var address = '{"address":"' + details.formatted_address + '"}';
var phone = '{"phone":"' + details.formatted_phone_number+ '"}';
var website = '{"website":"' + details.website + '"}';
var full_address = name + "," + address + "," + phone + "," + website;
console.log(full_address);
var jsonTxt = JSON.stringify(full_address);
}
}
function gpsFail() {
//Geo-location is supported, but we failed to get your coordinates.
}
Try this.
Here you need to give radius according to your distance. Types may be ATM, Restaurants, Gas Station the way you needs.
You need to give places like Chennai, Bangalore, etc or you provide latitude/longitude. Describe it briefly. You in android/iphone

Google Map implementation not working on Safari and Chrome

I am implementing a google map on the contact page of this website:
http://www.vqt.ch/dev/?lang=fr&page=contact
The map displays in the rectangle on the top of the page. Everything is working fine on Firefox, but nothing is displayed on Safari & Chrome...
Here is the way I implement it:
<script src="http://maps.google.com/maps?file=api&v=2&key=ABQIAAAA8yt4eBY5BILk0ExOfUVIuxTtIfr4IreHJHupahKP7IIqKlsN7BQG4crqM32UzthNoFP_54xDooNNNQ&sensor=true" type="text/javascript"></script>
<script type="text/javascript">
//<![CDATA[
function createMarker(point,text) {
var marker = new GMarker(point);
GEvent.addListener(marker, "click", function() { marker.openInfoWindowHtml(text); });
return marker;
}
function load() {
if (GBrowserIsCompatible()) {
var Lat=46.983707;
var Lng=6.904106;
var Zoom=13;
var TextAffiche="<strong>VQT<\/song><br/>Verre & Quartz Technique SA<br/><br/>Rue de Maillefer 11d<br/>2000 Neuchatel";
var map = new GMap2(document.getElementById("contactMap"));
map.setCenter(new GLatLng(Lat,Lng ),Zoom );
map.addControl(new GLargeMapControl3D());
map.addControl(new GMapTypeControl());
var point = new GLatLng(Lat,Lng);
var new_icon = new GIcon()
new_icon.image = "http://www.vqt.ch/gmap_marker.png";
new_icon.size = new GSize(50, 32);
new_icon.iconAnchor = new GPoint(0,0);
new_icon.infoWindowAnchor = new GPoint(0,0);
var opt;
opt = {};
opt.icon = new_icon;
opt.draggable = false;
opt.clickable = true;
opt.dragCrossMove = false;
var marker = new GMarker(point,opt);//createMarker(point,TextAffiche);
map.addOverlay(marker);
marker.openInfoWindowHtml(TextAffiche)
}
}
$("body").attr("onload", "load()");
$("body").attr("onunload", "GUnload()");
//]]>
</script>
and here is my html:
<div class="normalContent">
<div id="contactMap" class="borderedImages"></div>
</div>
Do you know what is wrong in there? I really don't understand why it's working somewhere and not working somewhere else...
Thank you for your help!
I restarted from a tutorial and it's now working:
http://www.vqt.ch/dev/google_map_debug/
The main difference is the call of the load function, which now is on the body attributes:
<body onload="load()" onunload="GUnload()">
So I guess the problem was here...
Thank you for your help!

How to display KML file using javascript

How to display google earth (KML) file using javascript.
thanks
I'll assume you want to view the KML-file in a browser preferably Mozilla Firefox. Firstly, I want to give some simple JavaScript that we will use in OpenLayers. You should try them since it also using JavaScript library.
Here I briefly show you how the codes are written.
<html>
<head>
<title>Google Layer with KML file</title>
<link rel="stylesheet" href="http://openlayers.org/api/theme/default/style.css" type="text/css" />
<link rel="stylesheet" href="http://openlayers.org/dev/examples/style.css" type="text/css" />
<script src='http://maps.google.com/maps?file=api&v=2&key=ABQIAAAAl9RMqSzhPUXAfeBCXOussRTQDbvAygy0cfGJr8dEMAYKf3RWNBQqP9mjKIsqTfmAlz5LOJ3Xpy5s4w'></script>
<script src="http://openlayers.org/api/OpenLayers.js"></script>
<script type="text/javascript">
var map;
function init() {
// Create the map object
map = new OpenLayers.Map('map');
// Create a Google layer
var gmap = new OpenLayers.Layer.Google(
"Google Streets", // the default
{numZoomLevels: 20}
);
// Add layer to map
map.addLayer(gmap);
//Adding KML file to map
map.addLayer(new OpenLayers.Layer.GML("KML", "kompleks_antarabangsa.kml",
{
format: OpenLayers.Format.KML,
formatOptions: {
extractStyles: true,
extractAttributes: true,
maxDepth: 2
}
}));
// Zoom to Kuala Lumpur, Malaysia
map.setCenter(new OpenLayers.LonLat(101.686855,3.139003), 13);
}
</script>
</head>
<body onload="init()">
<h1 id="title">Google Layer with KML file</h1>
<div id="map" style='width: 700px; height: 700px'></div>
</body>
</html>
As you can see, there is a small orange dot on the map. That is the KML file loaded on Google Maps.
Try and run the HTML codes using any software. But, I suggest you to use Notepad ++. Last but not least, I hope my answer isn't too late for you, Kyathi.
//do axis call to the data url
// parse the records to get the point and additional data
//plot like this
var features_1 = new Array(records.length -1);
for (var i = 1; i < records.length; i++) {
var coordinates = transform([ records[i][9], records[i][8]], 'EPSG:4326', 'EPSG:3857');
features_1[i-1] = new Feature( {
geometry: new Point(coordinates ),
name: records[i][6],
Magnitude: dat[i][dat[0].length -1],
size : dat[i][dat[0].length -1]
}) ;
}
var source = new VectorSource({
features: features_1
});
var clusterSource = new Cluster({
distance: 30,
source: source
});
vector = new VectorLayer({
source: clusterSource,
style: styleFunction
});
var raster = new TileLayer({
source: new Stamen({
layer: 'toner'
})
});
var map = new Map({
layers: [raster, vector],
interactions: defaultInteractions().extend([new Select({
condition: function(evt) {
return evt.type == 'pointermove' ||
evt.type == 'singleclick';
},
style: selectStyleFunction
})]),
target: 'map',
view: new View({
center: [0, 0],
zoom: 2
})
});
//