Google-maps geocoding service - javascript

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

Related

Direction Service Google API, draggable origin

For the start, i will key in origin and destination and it will show the displayed route from origin A to destination B. However, i would like to make the origin A draggable such that it will recalculate the route and display to me.
var directionsDisplay = new google.maps.DirectionsRenderer;
var directionsService = new google.maps.DirectionsService;
var map = new google.maps.Map(document.getElementById('map'), {
mapTypeControl: false,
center: {lat: 1.317206, lng: 103.772240},
zoom: 13
});
new AutocompleteDirectionsHandler(map);
directionsDisplay.setMap(map);
directionsDisplay.setPanel(document.getElementById('right-panel'));
var onChangeHandler = function() {
calculateAndDisplayRoute(directionsService, directionsDisplay);
};
document.getElementById('destination-input').addEventListener('change',
onChangeHandler);
}
function calculateAndDisplayRoute(directionsService,
directionsDisplay) {
var start = document.getElementById('origin-input').value;
var end = document.getElementById('destination-input').value;
directionsService.route({
origin: start,
destination: end,
travelMode: 'DRIVING'
}, function(response, status) {
if (status === 'OK') {
directionsDisplay.setDirections(response);
}
});
}
The HTML code is provided below.
<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>
</body>
Below is the screenshot of the current project i have.
Screenshot
Please try:
function initMap() {
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: {lat: -24.345, lng: 134.46} // Australia.
});
var directionsService = new google.maps.DirectionsService;
var directionsDisplay = new google.maps.DirectionsRenderer({
draggable: true,
map: map,
});
displayRoute('Perth, WA', 'Sydney, NSW', directionsService,
directionsDisplay);
}
function displayRoute(origin, destination, service, display) {
service.route({
origin: origin,
destination: destination,
travelMode: 'DRIVING',
avoidTolls: true
}, function(response, status) {
if (status === 'OK') {
display.setDirections(response);
} else {
alert('Could not display directions due to: ' + status);
}
});
}

Google map Blue-Dot for current location in reactjs

I was implementing google maps..And i want the default google blue dot for the current location. can anyone please tell, how to do so, in reactjs or in simple javascript..
First you have to allow the browser to send your Geo location to Google API, then wire up this code on the window/document load event :
var map, infoWindow;
function initMap() {
map = new google.maps.Map(document.getElementById('map'), {
center: { lat: -34.397, lng: 150.644 },
zoom: 6
});
infoWindow = new google.maps.InfoWindow;
// Try HTML5 geolocation.
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
var pos = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
infoWindow.setPosition(pos);
infoWindow.setContent('Location found.');
infoWindow.open(map);
var marker = new google.maps.Marker({
position: pos,
map: map,
title: 'Hello World!',
icon: 'https://maps.google.com/mapfiles/kml/shapes/info-i_maps.png',
});
map.setCenter(pos);
}, function () {
//handleLocationError(true, infoWindow, map.getCenter());
});
} else {
// Browser doesn't support Geolocation
//handleLocationError(false, infoWindow, map.getCenter());
}
}

ERROR TypeError: Cannot read property '__e3_' of undefined

I'm developing a web app with angular 6. I integrated google maps but marker click event is returning me an error.
Help me, thanks in advance.
import { } from '#types/googlemaps';
#ViewChild('whereMap') gmapElement: any;
map: google.maps.Map;
marker: google.maps.Marker;
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
let marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
}
map initialized and marker is working fine, but im unable to fire click event.
i have called the initMapp() in ngOnInit().
The navigator.geolocation.getCurrentPosition is asynchronous, you are likely meeting a race condition. You should move google.maps.event.addListener inside geolocation callback, otherwise you can try to assign event listener before the marker element was created.
Google Maps JavaScript API error message ERROR TypeError: Cannot read property '__e3_' of undefined typically means that you try to assign event to non-existing DOM element.
Try the following
initMapp() {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
let location = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
this.map = new google.maps.Map(this.gmapElement.nativeElement, {
center: location,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
this.marker = new google.maps.Marker({
position: location,
map: this.map,
draggable: true,
animation: google.maps.Animation.DROP,
title: 'Got you!'
});
google.maps.event.addListener(this.marker, 'click', () => {
console.log('marker clicked');
});
});
} else {
alert("Geolocation is not supported by this browser.");
}
}
I hope this helps!

when applying styles to icons on fusion table, getting unexpected identifier

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"}}
]
});

Google Maps Autocomplete List

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.

Categories