Utilize Google Maps geocoding functionality to pinpoint a location and then

I've encountered this strange phenomenon, but first let's take a look at the code:

HTML

<div ng-app='maptesting'>
       <div ng-controller="MapCtrl">
            <div id="map_canvas" ui-map="myMap" 
              style="height:300px;width:400px;border:2px solid #777777;margin:3px;     
              border:1px solid" 
              ui-options="mapOptions" 
              ui-event="{'map-idle' : 'onMapIdle()'}"
    >
</div>

JavaScript

angular.module('maptesting', ['ui.map','ui.event']);
function MapCtrl($scope) {
    var ll = new google.maps.LatLng(30.9000, 40.2740);
    $scope.mapOptions = {
        center: ll,
        zoom: 15,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var geocoder= new google.maps.Geocoder();

var map = new window.google.maps.Map(document.getElementById("map_canvas"),      
    $scope.mapOptions);

var address='los angeles';
geocoder.geocode({'address':address},function(results,status){
    if (status == google.maps.GeocoderStatus.OK){
        alert(address);
        alert(results[0].geometry.location);
        alert($scope.myMap);
        map.setCenter(results[0].geometry.location);
        test=results[0].geometry.location;
        var marker=new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
    }else{
        alert(status);
    }   
});


$scope.onMapIdle = function() {
    if ($scope.myMarkers === undefined){    
        var marker = new google.maps.Marker({
            map: $scope.myMap,
            position: ll
        });
        $scope.myMarkers = [marker, ];
    }
};

$scope.markerClicked = function(m) {
    window.alert("clicked");
};

}

Everything appears to be functioning correctly - markers, zoom, drag - except for the map.setCenter which always defaults to the coordinates of ll. Can anyone offer some guidance?

You can view a fiddle here. As you'll notice, the center is not in California as expected, but rather in Iraq. Additionally, if you zoom quickly, it seems like there are two maps overlapping.

Answer №1

You currently have two instances of google.maps.Map in your code - one created using ui.map and another created in MapCtrl.

To optimize your code, remove the creation of the second instance and replace it with the following code:

//Markers should be added once map is loaded
    var address = 'Los Angeles';
    geocoder.geocode({'address': address}, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            alert(address);
            alert(results[0].geometry.location);
            alert($scope.myMap);
            $scope.myMap.setCenter(results[0].geometry.location);
            test = results[0].geometry.location;
            var marker = new google.maps.Marker({
                map: $scope.myMap,
                position: results[0].geometry.location
            });
        } else {
            alert(status);
        }
    });

Check out this JSFiddle for reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Protractor timeouts when working with AngularJS

I'm currently facing challenges with conducting end-to-end (e2e) tests using Protractor and Angularjs. I've utilized a sample test project available at the following link: https://github.com/mbcooper/ProtractorExample. Regrettably, Protractor is ...

Choosing the subsequent element that comes before

<tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> <tr class="main"></tr> <tr class="emails-details"> <button>some button</button> </tr> &l ...

Ways to verify whether any of the variables exceed 0

Is there a more concise way in Typescript to check if any of the variables are greater than 0? How can I refactor the code below for elegance and brevity? checkIfNonZero():boolean{ const a=0; const b=1; const c=0; const d=0; // Instead of ma ...

Solution for displaying table cells in IE 7 and lower using Javascript

Lately, the community has come up with some amazing tools to push early versions of IE beyond their intended capabilities. For example, using multi-column CSS selectors. However, I've been struggling to find a JavaScript that can be loaded conditional ...

Is it possible to use jQuery to refresh only a section of the page and modify the URL at the same time?

There is a page (http://myflashpics.com/picture/p9e0) that displays user information along with a small thumbnail on the side. Currently, when clicking on the image, it redirects to a different page and the sidebar reloads as well. I am curious if it' ...

What is the best way to identify a specific list item from a dropdown menu and determine its position on

Check out my jsfiddle for reference. My goal is to calculate scores based on different options selected, specifically relating to radiation types. I'm struggling with assigning a score to each type of radiation and integrating the drop-down menu selec ...

Develop a Modal Form using Bootstrap (HTML)

I followed a tutorial on creating a modal form with Bootstrap, you can find it here: http://www.youtube.com/watch?v=HCEbp07hfLw I replicated the steps shown in the video, but when I try to open the page in my browser, nothing appears. I have added the Bo ...

What is the best way to reduce the file size of a group of PNG images for

For my game character, I have a collection of PNG files including stand.png, run1.png, run2.png. To display a series of actions on the JavaScript canvas, I need to load these images. However, the size of each .png file adds up quickly – for example, it ...

What is the best way to transform object request data into a string in an Express application using Node.js

I am trying to save the request data from app.get('/') to a variable, but I keep getting an error "TypeError: Converting circular structure to JSON". var express = require('express') var app = express() var bodyParser = require('b ...

Error: Attempting to access a property of an undefined value (referencing '8') was unsuccessful

Hello everyone, I am new to posting and identify as a junior Frontend developer. I'm encountering a confusing issue with the InputLabel from Material UI (ver. 5) on a specific section of the website I'm working on. On the homepage, I successfully ...

Using Node.js to import modules without the need for assignment

In my recent project, I decided to organize my express application by putting all of my routes in a separate file named routes.js: module.exports = function(server) { // Server represents the Express object server.get('/something', (req, res) ...

Can anyone offer a straightforward method for obtaining JavaScript output in Java within the Eclipse environment?

Currently, I am attempting to retrieve the return value from a JavaScript function that I have created. Although I can achieve this using a complex method involving listeners, I am interested in utilizing Eclipse's Browser.evaluate method. For practi ...

Learn how to instruct ajax to fetch the designated information and retrieve corresponding data from the database based on the selected criteria

Looking for some help with my 2 select boxes. The first box allows users to choose a brand, while the second box should display products from that brand fetched from the database. Unfortunately, I'm not familiar with AJAX and the script provided by a ...

What is the best way to apply a texture to a triangle using three.js?

I've been able to add textures to cubes, spheres, and other primitives in a scene I created. However, when it comes to adding a texture to a simple triangle, I'm encountering difficulties. Below is my attempt at achieving this: var texture=TH ...

Tips for displaying data by using the append() function when the page is scrolled to the bottom

How can I use the append() function to display data when scrolling to the bottom of the page? Initially, when you load the page index.php, it will display 88888 and more br tags When you scroll to the bottom of the page, I want to show 88888 and more br ...

Ability to access functions from required modules that are defined within the calling module

Is there a way to call a function within a required module that is defined in the main program without copying or creating separate files? Main.js: var http = require('http'); var aFunc = function() {return 1;} var bFunc = require('./bFunc ...

Trouble with Mongoose adding items to an array

ReviewSchema with Mongoose: import mongoose from "mongoose"; const ReviewSchema = new mongoose.Schema({ likes: { type: Number, required: true, default: 0, }, reactedBy: [ { required: true, ...

endless update cycle in Vue

I'm currently working on developing a custom component. And I have an idea of how I want to use it: let app = new Vue({ el:'#app', template:` <tab> <tab-item name='1'> <h1> This is tab item 1& ...

Ways to troubleshoot and verify values in PHP that are sent through AJAX

In my jQuery function, I am using AJAX to send values to a PHP file: $.ajax({ //make ajax request to cart_process.php url: "cart_process.php", type: "POST", dataType: "json", //expect json value from server data: { quantity: iqty, ...

"Transmitting an ajax POST call and receiving a corresponding GET response

Currently, I am utilizing the following AJAX code: $.ajax({ url: "Editor.aspx/Page_LoadComplete", data: { "contentCheckCode": contents }, type: "POST", success: function (response) { alert("Contents saved..."); }, error: fu ...