function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: {lat: 24.149950, lng: 120.638610},
mapId: '63d22d3ae6cf15ff'
});
console.log(getCoordinates("Bouverie Street"));
}
// geocoder
function getCoordinates(address) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode({address: address}, (results, status) => {
if (status === 'OK') {
return results[0].geometry.location;
} else {
alert("Geocode error: " + status);
console.log(("Geocode error: " + status));
}
});
}
On line 9 I'm trying to log the return object from getCoordinates(). However it shows up as undefined for some reason. I think the function works as intended as, if I added "console.log(results);" above the return statement, it logs the result object as intended.
if (status === 'OK') {
return results[0].geometry.location;
}
What am I doing wrong? Thanks in advance.
There has occurred an asynchronous issue. To get rid of that(in this case, you're printing latitude and longitude) you can pass a callback parameter when you're calling getCoordinates function.
Here I'm going to use below script for the example:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=initMap" defer></script>
So replace this with your own which will be like this:
<script type="text/javascript" src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY&callback=initMap" defer></script>
So here I'm going to pass a callback parameter to getCoordinates function which will print coordinates passed from getCoordinates in this way:
function initMap() {
const map = new google.maps.Map(document.getElementById("map"), {
zoom: 15,
center: { lat: 24.149950, lng: 120.638610 },
mapId: '63d22d3ae6cf15ff'
});
getCoordinates("Bouverie Street", printLocation);
}
function printLocation(location) {
console.log("location");
console.log(location.lat());
console.log(location.lng());
}
// geocoder
function getCoordinates(address, myCallback) {
const geocoder = new google.maps.Geocoder();
geocoder.geocode({ address: address }, (results, status) => {
if (status === 'OK') {
myCallback(results[0].geometry.location);
} else {
console.warn = () => {}; // stop printing warnings
console.log(("Geocode error: " + status));
}
});
}
#map {
height: 400px;
width: 100%;
}
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&callback=initMap" defer></script>
<div id="map"></div>
Related
I'm working with the Google Maps Geocoder service for AngularJS framework, but hadn't been able to show any markers so far.
Everything else seems to be working fine, but I really need the markers.
Here's my app.js:
angular.module('modelApp', ['ngAnimate', 'ui.bootstrap', 'google-maps'])
.factory('MarkerCreatorService', function () {
var markerId = 0;
function create(latitude, longitude) {
var marker = {
options: {
animation: 1,
labelAnchor: "28 -5",
labelClass: 'markerlabel'
},
latitude: latitude,
longitude: longitude,
id: ++markerId
};
return marker;
}
function invokeSuccessCallback(successCallback, marker) {
if (typeof successCallback === 'function') {
successCallback(marker);
}
}
function createByAddress(address, successCallback) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
var results = results[0];
invokeSuccessCallback(successCallback, marker);
} else {
alert("Unknown address: " + address);
}
});
}
return {
create: create,
createByAddress: createByAddress
};
})
.controller('modelCtrl', function ($scope, $http, $timeout, $q, $log, MarkerCreatorService){
// $ajax Init
$scope.model= [];
$http.get('resources/model.json')
.success(function(data){
$scope.model= data;
})
$scope.address = '';
$scope.map = {
center: {
latitude: 0,
longitude: 0
},
zoom: 2,
markers: [],
control: {},
options: {
scrollwheel: false
}
};
$scope.map.markers.push($scope.autentiaMarker);
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address, function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
function refresh(marker) {
$scope.map.control.refresh({
latitude: marker.latitude,
longitude: marker.longitude});
$scope.map.zoom = 5;
}
})
Here's the index.html:
<google-map center="map.center"
zoom="map.zoom"
draggable="true"
options="map.options"
control="map.control">
<markers models="map.markers" coords="'self'" options="'options'"
isLabel="true">
</marker>
</google-map>
So, I basically need to show the markers. Do you have any idea about what's wrong with my code?
Any help would be appreciated.
One approach is to convert the callback-based API to a promise-based API:
app.factory('MarkerCreatorService', function ($q) {
//...
function createByAddress(address) {
var geocoder = new google.maps.Geocoder();
var deferred = $q.defer();
geocoder.geocode({'address' : address}, function (results, status) {
if (status === google.maps.GeocoderStatus.OK) {
var firstAddress = results[0];
var latitude = firstAddress.geometry.location.lat();
var longitude = firstAddress.geometry.location.lng();
var marker = create(latitude, longitude);
var results = results[0];
deferred.resolve(marker);
} else {
alert("Unknown address: " + address);
deferred.reject("Unknown address: " + address);
}
});
return deferred.promise;
}
//...
});
Usage
$scope.addAddress = function() {
var address = $scope.address;
if (address !== '') {
MarkerCreatorService.createByAddress(address).then(function(marker) {
$scope.map.markers.push(marker);
refresh(marker);
});
}
};
By converting it to AngularJS promise, it integrates the API into the AngularJS framework and its digest cycle. Only operations which are applied in the AngularJS execution context will benefit from AngularJS data-binding, exception handling, property watching, etc.
I get reference from here : How to get the formatted address from a dragged marker in Google Version Maps
It using javascript
I want to implement it in the vue component
I try like this :
https://jsfiddle.net/oscar11/1krtvcfj/2/
I don't type code here. Because the code is too much. So you can directly see in jsfiddle
If I click geocode button, there exist error like this :
Uncaught ReferenceError: marker is not defined
How can I solve the error?
new Vue({
el: '#app',
template: `
<div>
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" #click="codeAddress()">
</div>
`,
data() {
return {
geocoder: null,
map: null,
marker: null,
infowindow: null
}
},
mounted() {
this.infowindow = new google.maps.InfoWindow({
size: new google.maps.Size(150, 50)
})
google.maps.event.addDomListener(window, "load", this.initialize)
},
methods: {
initialize() {
this.geocoder = new google.maps.Geocoder();
let latlng = new google.maps.LatLng(-34.397, 150.644)
let mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(document.getElementById('map_canvas'), mapOptions)
google.maps.event.addListener(this.map, 'click', () => {
this.infowindow.close()
});
},
geocodePosition(pos) {
this.geocoder.geocode({
latLng: pos
}, responses => {
if (responses && responses.length > 0) {
this.marker.formatted_address = responses[0].formatted_address
} else {
this.marker.formatted_address = 'Cannot determine address at this location.'
}
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6))
this.infowindow.open(this.map, this.marker)
});
},
codeAddress() {
let address = document.getElementById('address').value;
this.geocoder.geocode({
'address': address
}, (results, status) => {
if (status == google.maps.GeocoderStatus.OK) {
this.map.setCenter(results[0].geometry.location);
if (this.marker) {
this.marker.setMap(null);
if (this.infowindow) this.infowindow.close();
}
this.marker = new google.maps.Marker({
map: this.map,
draggable: true,
position: results[0].geometry.location
});
google.maps.event.addListener(this.marker, 'dragend', () => {
this.geocodePosition(this.marker.getPosition());
});
google.maps.event.addListener(this.marker, 'click', () => {
if (this.marker.formatted_address) {
this.infowindow.setContent(this.marker.formatted_address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
} else {
this.infowindow.setContent(address + "<br>coordinates: " + this.marker.getPosition().toUrlValue(6));
}
this.infowindow.open(this.map, this.marker);
});
google.maps.event.trigger(this.marker, 'click');
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
}
})
You should store globe value in the data of Vue component, and get the value by this.name in you methods.
I would like to create a link that open a new google map tab with route from navigator.geolocation.getCurrentPosition to a specific placeId.
If there is geolocation a problem then, open a new tab without origin completed
Here is what I try:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
latitude: 48.925606,
longitude: 2.327621,
};
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
$('.js-ItinaryFromI').on('click', () => {
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
}, () => {
// The problem seems to come from this line :
window.open(`https://www.google.com/maps/dir/origin=pos&destination=place_id:${options.placeId}&travelmode=driving`, '_blank');
});
} else {
// And this line
window.open(`https://www.google.com/maps/dir//place_id${options.placeId}&travelmode=driving`, '_blank');
}
});
Any idea please ?
You should use Google Maps Directions API if you wanted to calculate directions between location. You can search for directions for several modes of transportation, including transit, driving, walking, or cycling.
These parameters (origin, destination, travel_mode) are used in Google Maps Directions API and probably won't work well using Google Maps.
I also noticed in the code you provided that certain variables were not properly concatenated into the request. Hence, your request would not provide accurate results.
Here's a sample of valid request:
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=YOUR_API_KEY', '_blank');
Don't forget to include your API key in each request.
I modified your code a bit. You can check it below:
const options = {
placeId: 'ChIJDyx4bNhu5kcRqJ3RkAPGMEk',
//placeId: 'ChIJ51Ic7BXIlzMRK2WH8qoM6Ek',
latitude: 48.925606,
longitude: 2.327621,
};
function initMap() {
const mapOptions = {
zoom: 15,
center: new google.maps.LatLng(options.latitude, options.longitude),
};
const map = new google.maps.Map(document.getElementById('Map'), mapOptions);
const service = new google.maps.places.PlacesService(map);
service.getDetails({
placeId: options.placeId,
}, (result, status) => {
if (status !== google.maps.places.PlacesServiceStatus.OK) {
alert(status);
return;
}
const marker = new google.maps.Marker({
map: map,
position: result.geometry.location,
});
});
if ( navigator.geolocation ) {
navigator.geolocation.getCurrentPosition((position) => {
const pos = {
lat: position.coords.latitude,
lng: position.coords.longitude,
};
document.getElementById('js-ItinaryFromI').addEventListener('click', () => {
window.open('https://maps.googleapis.com/maps/api/directions/json?origin='+pos.lat+','+pos.lng+'&destination=place_id:'+options.placeId+'&travelmode=driving&key=[API-KEY]', '_blank');
});
});
} else {
alert('Geolocation not found!');
}
}
html,body,#Map {
width:100%;
height:100%;
}
<button id="js-ItinaryFromI">Click Me</button>
<div id="Map" ></div>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCzjs-bUR6iIl8yGLr60p6-zbdFtRpuXTQ&callback=initMap&libraries=places">
</script>
You can try this using JSBin. For some reason it doesn't work here in Stackoverflow's code snippet. I don't know why.
Good luck and happy coding!
i'm not getting google map in ionic 3 i'm using plain javascript so i think it is not displaying in my mobile.
here is my code
geocodeLatLng(lat, lng) {
var geocoder = new google.maps.Geocoder;
var latlng = {
lat: lat,
lng: lng
};
geocoder.geocode({
'location': latlng
}, (results, status) => {
if (status === 'OK') {
if (results[0]) {
console.log(results[0].formatted_address);
} else {
window.alert('No results found');
}
} else {
window.alert('Geocoder failed due to: ' + status);
}
});
}
here is demo online: how to get current postion name using google map api
i tried to convert it to ionic 3
import { Geolocation } from '#ionic-native/geolocation';
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
let latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
// don't know further steps
}, (err) => {
console.log(err);
});
}
Question i want to achieve same result as this with ionic 3:how to get current postion name using google map api
First install the google map library using this,
npm install #types/googlemaps --save-dev
Now go to node_modules and then #types and inside that googlemaps folder and add below line,
declare module 'googlemaps';
Then import google map module in your component file,
import { Geolocation ,GeolocationOptions } from '#ionic-native/geolocation';
import { googlemaps } from 'googlemaps';
export class HomePage {
#ViewChild('map') mapElement: ElementRef;
map:any;
latLng:any;
mapOptions:any;
constructor(private geolocation : Geolocation){ }
ionViewDidLoad(){
this.loadMap();
}
loadMap(){
this.geolocation.getCurrentPosition().then((position) => {
this.latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
console.log('latLng',this.latLng);
this.mapOptions = {
center: this.latLng,
zoom: 14,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
this.map = new google.maps.Map(this.mapElement.nativeElement, this.mapOptions);
}, (err) => {
alert('err '+err);
});
}
}
Now add this code in your HTML file,
<div #map id="map"></div>
Thanks,
I'm attempting to implement a Google Map on my Meteor app that will get the user's location and then will find places that serve food near the user. I began by implementing the example
given by Google, and it worked fine when I did it that way; however I'm trying to implement it properly by adding it to the actual Javascript file and it is now giving me a "Google is undefined" error.
menuList = new Mongo.Collection('items');
if (Meteor.isClient) {
var pls;
var map;
var infowindow;
Meteor.startup(function () {
//get user location and return location in console
var options = {
enableHighAccuracy: true,
timeout: 5000,
maximumAge: 0
};
function success(pos) {
var crd = pos.coords;
console.log('Your current position is:');
console.log('Latitude : ' + crd.latitude);
console.log('Longitude: ' + crd.longitude);
console.log('More or less ' + crd.accuracy + ' meters.');
pls = {lat: crd.latitude, lng: crd.longitude};
};
function error(err) {
console.warn('ERROR(' + err.code + '): ' + err.message);
};
navigator.geolocation.getCurrentPosition(success, error, options);
})
Meteor.methods({
callback: function (results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
},
createMarker: function (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(place.name);
infowindow.open(map, this);
});
}
})
Template.searchIt.helpers({
'initMap': function () {
console.log("HERE");
//Dummy values I placed for StackOverflow
var pyrmont = {lat: -33.234, lng: 95.343};
map = new google.maps.Map(document.getElementById('map'), {
center: pyrmont,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: pyrmont,
radius: 500,
types: ['food']
}, callback);
}
})
}
<head>
<title>Place searches</title>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<div id="map"></div>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyACgaDFJrh2pMm-bSta1S40wpKDDSpXO2M
&signed_in=true&libraries=places" async defer></script>
<style>
html, body {
height: 100%;
margin: 0;
padding: 0;
}
#map {
height: 100%;
}
</style>
</head>
<body>
{{>searchIt}}
</body>
<template name="searchIt">
{{initMap}}
</template>
You should try the dburles:google-maps package.
Here is an example written by its author: http://meteorcapture.com/how-to-create-a-reactive-google-map/
Have fun!
i had to place the code you have above inside of a GoogleMaps.ready('map', callback) block. or inside of an if (GoogleMaps.loaded()) {} block...
for instance.. this works just fine:
caveat: i'm using the radarSearch, but the concept is the same.
Template.galleryCard.onRendered(function() {
GoogleMaps.ready('minimap', function(map) {
const params = {
map: map,
name: 'The Spice Suite',
loc: {lat: 38.9738619, lng: -77.01829699999999},
};
const service = new google.maps.places.PlacesService(params.map.instance);
let request2 = {
//name & location & radius (meters).
name: params.name,
location: params.loc,
radius: 100,
};
let callback = function(results,status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
console.log(results[0]);
return results[0].place_id;
} else {
console.log(status);
}
};
service.radarSearch(request2,callback);
});
});